Spring Boot 2.0 教程 - 深入SpringAplication
原文连接:https://www.codemore.top/cates/Backend/post/2018-05-20/spring-boot-SpringApplication
可以通过SpringApplication.run() 方法轻松的启动一个Spring应用,例如
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
运行结果
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: v2.0.1.RELEASE
2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080
2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658)
默认的Log级别是INFO级别.
定制banner
banner是在Spring应用启动的时候打印的,如果需要定制banner,可以添加banner.txt到classpath中,或者设置spring.banner.location属性设置banner的路径。banner默认编码方式是UTF-8,如果不使用UTF-8,可以设置spring.banner.charset属性设置其编码方式。除了文本文件,也可以使用,banner.gif,banner.jpeg,banner.png等图片文件作为banner,或者设置spring.banner.image.location属性设置图片banner。图片有Spring转为ASCII输出。 banner.txt 中添加如下占位符
- ${application.version} 在
MANIFEST.MF中定义的版本号,例如Implementation-Version: 1.0则版本号为 1.0 - ${application.formatted-version} 版本号格式化加V 例如 v1.0
- ${spring-boot.version} 使用的Spring Boot的版本,例如 2.0.1.RELEASE
- ${spring-boot.formatted-version} 版本号加V,例如v2.0.1.RELEASE
- ${Ansi.NAME},${AnsiColor.NAME} ,${AnsiBackground.NAME},${AnsiStyle.NAME} ANSI escape code名
${application.title} MANIFEST.MF 定义的应用名,例如
Implemention-Title: MyApp取MyApp
也可以实现org.springframework.boot.Banner接口的printBanner()方法定制Banner,使用SpringApplication.setBanner()设置banner。 配置spring.main.banner-mode设置是否在控制台显示banner
定制SpringApplication
可以通过创建自定义的SpringApplication示例来定制SpringApplication,例如
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
使用builder定制SpringApplication
new SpringApplicationBuilder()
.sources(Parent.class)
.child(Application.class)
.bannerMode(Banner.Mode.OFF)
.run(args);
应用事件和监听器
除了通常的Spring Framework的事件,例如ContextRefreshedEvent等,SpringApplication还会发送一些其他的应用时间。 由于一些事件是在ApplicationContext创建之前触发的,因此无法通过@Bean的方式注册这些事件的监听器。可以使用SpringApplication.addListeners() 犯法或者SpringApplicationBuilder.listeners()方法注册监听器。 也可以通过添加META-INF/spring.factories文件到项目中,自动注册监听器,例如org.springframework.context.ApplicationListener=come.example.project.MyListener 应用启动后,应用时间按照如下的顺序触发 1. 应用开始运行时触发ApplicationStartingEvent事件 2. 在ApplicationContext创建之前,Environment可用时触发ApplicationEnvironmentPreparedEvent事件。 3. bean定义加载后,刷新之前触发ApplicationPreparedEvent事件 4. context刷新后,command-line runner运行前,触发ApplicationStartedEvent 5. command-lie runner运行后,触发ApplicationReadyEvent表示应用可以接受请求了 6. 如果发生异常,触发ApplicationFailedEvent 应用事件时通过Spring Framework的事件发布机制发送的,这种机制保证了发送给子context的事件同样也会发送给其祖先context。因此如果ApplicationContext时有层次的,可能会收到多个相同的事件,为了区分这些事件,需要应用注入自己的ApplicationContext,当接收事件时判断是否时本层事件再做处理,可以用过继承ApplicationContextAware注入ApplicationContext,或者如果监听器时一个bean也可以用过@Autowired注入ApplicationContext。
Web环境
SpringApplication可以根据配置创建正确的ApplicationContext
- 如果提供了Spring MVC,则使用
AnnotationConfigServletWebServerApplicationContext - 如果Spring MVC未提供,而提供了WebFlux 则使用
AnnotationConfigReactiveWebApplicationContext。 如果都没提供则使用
AnnotationConfigApplicationContext
同样也可以使用setApplication(...)完全自己设置ApplicationContext。
访问应用参数
如果需要访问SpringApplication.run(...)中的args参数,可以通过注入org.springframework.boot.ApplicationArguments bean访问。接口ApplicationArguments不仅提供了访问原生参数的String[] ,同样也提供了 option和non-option参数例如
import org.springframework.boot.*
import org.springframework.beans.factory.annotation.*
import org.springframework.stereotype.*
@Component
public class MyBean {
@Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
// if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
}
}
使用ApplicationRunner和CommandLineRunner
如果在运行完SpringApplication.run()之后需要运行其他代码,可以通过实现ApplicationRunner或者CommandLineRunner接口,这俩接口作用相同,都提供一个run()的方法,等调用完SpringApplication.run()之后调用,例如:
import org.springframework.boot.*
import org.springframework.stereotype.*
@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) {
// Do something...
}
}
如果定义了多个CommandLineRunner或者ApplicationRunner,则可以通过接口org.springframework.core.Ordered或者org.springframework.core.annotation.Order注解提供顺序。
应用退出
每一个SpringApplication都会注册一个JVM退出的钩子,保证ApplicationContext可以优雅关闭。另外bean可以实现org.springfamework.boot.ExitCodeGenerator接口当调用SpringApplication.exit()时返回一个特定的返回码,这个返回码可以传递给System.exit()例如:
@SpringBootApplication
public class ExitCodeApplication {
@Bean
public ExitCodeGenerator exitCodeGenerator() {
return () -> 42;
}
public static void main(String[] args) {
System.exit(SpringApplication
.exit(SpringApplication.run(ExitCodeApplication.class, args)));
}
}
Spring Boot 2.0 教程 - 深入SpringAplication的更多相关文章
- Spring Boot 2.0 教程 | AOP 切面统一打印请求日志
欢迎关注微信公众号: 小哈学Java 文章首发于个人网站 https://www.exception.site/springboot/spring-boot-aop-web-request 本节中,您 ...
- Spring Boot 2.0 教程 | @ModelAttribute 注解
欢迎关注微信公众号: 小哈学Java 文章首发于个人网站: https://www.exception.site/springboot/spring-boot-model-attribute Spri ...
- Spring Boot 2.0 教程 | 配置 Undertow 容器
欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 文章首发于个人网站 https://ww ...
- Spring Boot 2.0 教程 - 配置详解
Spring Boot 可以通过properties文件,YAML文件,环境变量和命令行参数进行配置.属性值可以通过,@Value注解,Environment或者ConfigurationProper ...
- Spring Boot 2.0 教程 | 快速集成整合消息中间件 Kafka
欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...
- Spring Boot 2.0 图文教程 | 集成邮件发送功能
文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...
- Spring Boot 2.0 的快速入门(图文教程)
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...
- Spring Boot 2.0(六):使用 Docker 部署 Spring Boot 开源软件云收藏
云收藏项目已经开源2年多了,作为当初刚开始学习 Spring Boot 的练手项目,使用了很多当时很新的技术,现在看来其实很多新技术是没有必要使用的,但做为学习案例来讲确实是一个绝佳的 Spring ...
- Spring Boot 2.0 升级指南
Spring Boot 2.0 升级指南 前言 Spring Boot已经发布2.0有5个月多,多了很多新特性,一些坑也慢慢被填上,最近有空,就把项目中Spring Boot 版本做了升级,顺便整理下 ...
随机推荐
- android 之ViewStub
在开发应用程序的时候,经常会遇到这样的情况,会在运行时动态根据条件来决定显示哪个View或某个布局.那么最通常的想法就是把可能用到的View都写在上面,先把它们的可见性都设为View.GONE,然后在 ...
- C语言笔试经典--求分数数列的和
题目: 求数组的和 2 3/2 5/3 8/5 13/8 21/13 ... 求前20项的和 //求分数数列的和 #include<stdio.h> // ...
- Java 去掉字符串中的换行符回车符等
去掉一个字符串中的换行符.回车符等,将连续多个空格替换成一个空格 String string = "this just a test" Pattern p = Pattern.co ...
- PHP变量的定义与相应的数据类型
在PHP中,变量的定义和C语言定义的方法是类似的,但是在PHP中,变量使用起来就非常灵活,一个变量既可以做整型,也可以是浮点型,也可以是字符串或者字符类型,通通只要在变量名前面加一个$然后加上你的变量 ...
- [Zabbix3.0] 添加MySQL监控
zabbix3.0 server已经自带MySQL的模板了,只要修改agent端,然在web端给主机添加模板就好了. Agent端操作 /etc/zabbix/zabbix_agentd.d/user ...
- java线程的同步控制--重入锁ReentrantLock
我们常用的synchronized关键字是一种最简单的线程同步控制方法,它决定了一个线程是否可以访问临界区资源.同时Object.wait() 和Object.notify()方法起到了线程等待和通知 ...
- Java中使用有返回值的线程
在创建多线程程序的时候,我们常实现Runnable接口,Runnable没有返回值,要想获得返回值,Java5提供了一个新的接口Callable,可以获取线程中的返回值,但是获取线程的返回值的时候,需 ...
- 深入了解Collections
在 Java集合类框架里有两个类叫做Collections(注意,不是Collection!)和Arrays,这是JCF里面功能强大的工具,但初学者往往会忽视.按JCF文档的说法,这两个类提供了封装器 ...
- 使用Python自动提取内容摘要
https://www.biaodianfu.com/automatic-text-summarizer.html 利用计算机将大量的文本进行处理,产生简洁.精炼内容的过程就是文本摘要,人们可通过阅读 ...
- Centos7查看IP
查看IP ip addr : lo: <LOOPBACK,UP,LOWER_UP> mtu qdisc noqueue state UNKNOWN qlen link/loopback : ...