原文连接: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的更多相关文章

  1. Spring Boot 2.0 教程 | AOP 切面统一打印请求日志

    欢迎关注微信公众号: 小哈学Java 文章首发于个人网站 https://www.exception.site/springboot/spring-boot-aop-web-request 本节中,您 ...

  2. Spring Boot 2.0 教程 | @ModelAttribute 注解

    欢迎关注微信公众号: 小哈学Java 文章首发于个人网站: https://www.exception.site/springboot/spring-boot-model-attribute Spri ...

  3. Spring Boot 2.0 教程 | 配置 Undertow 容器

    欢迎关注个人微信公众号: 小哈学Java, 文末分享阿里 P8 资深架构师吐血总结的 <Java 核心知识整理&面试.pdf>资源链接!! 文章首发于个人网站 https://ww ...

  4. Spring Boot 2.0 教程 - 配置详解

    Spring Boot 可以通过properties文件,YAML文件,环境变量和命令行参数进行配置.属性值可以通过,@Value注解,Environment或者ConfigurationProper ...

  5. Spring Boot 2.0 教程 | 快速集成整合消息中间件 Kafka

    欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...

  6. Spring Boot 2.0 图文教程 | 集成邮件发送功能

    文章首发自个人微信公众号: 小哈学Java 个人网站: https://www.exception.site/springboot/spring-boots-send-mail 大家好,后续会间断地奉 ...

  7. Spring Boot 2.0 的快速入门(图文教程)

    摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...

  8. Spring Boot 2.0(六):使用 Docker 部署 Spring Boot 开源软件云收藏

    云收藏项目已经开源2年多了,作为当初刚开始学习 Spring Boot 的练手项目,使用了很多当时很新的技术,现在看来其实很多新技术是没有必要使用的,但做为学习案例来讲确实是一个绝佳的 Spring ...

  9. Spring Boot 2.0 升级指南

    Spring Boot 2.0 升级指南 前言 Spring Boot已经发布2.0有5个月多,多了很多新特性,一些坑也慢慢被填上,最近有空,就把项目中Spring Boot 版本做了升级,顺便整理下 ...

随机推荐

  1. ERP-非财务人员的财务培训教(一.一)------基本会计知识

    一.基本会计知识 第一节 会计是企业的语言 反映企业经济状况的两组会计语言词汇 四个层次的会计语言规则 财务会计报告的组成 会计语言要素 会计工作主要是把企业杂乱的会计数据归纳整理,加工编制成有用的财 ...

  2. JFinal开发环境搭建,JFinal开发案例

     JFinal  是基于 Java  语言的极速  WEB  + ORM  开发框架,其核心设计目标是开发迅速.代码量少.学习简单.功能强大.轻量级.易扩展.Restful.在拥有Java 语言所 ...

  3. android本地音乐播放器

    乐乐音乐播放器更新到2.0版本了,之前1.0版本更多的是试验性实践,这次更新的2.0版本,更多的是将1.0的功能移植到2.0,在界面和皮肤风格上,参考了 天天动听 界面,在歌词显示方面 与 1.0 版 ...

  4. OpenCV——去雾

    这是一个简化的实现算法,完整的算法请参考: Single Image Haze Removal Using Dark Channel Prior --CVPR 2009 // define head ...

  5. C语言二维数组实现扫雷游戏

    #include<stdio.h> //使用二维数组实现 扫雷 int main() { char ui[8][8]={ '+','+','+','+','+','+','+','+', ...

  6. MOOS学习笔记3——命令行

    MOOS学习笔记3--命令行 例程 /** * @code A simple example showing how to use a comms client问问怎么样 */ #include &q ...

  7. sqlite 数据类型 <转>

    一般数据采用的固定的静态数据类型,而SQLite采用的是动态数据类型,会根据存入值自动判断.SQLite具有以下五种数据类型: 1.NULL:空值.2.INTEGER:带符号的整型,具体取决有存入数字 ...

  8. Javascript的console['']几种常用输入方法

    1.console.log是最常用的输入方法,正常化输出语句,还具有print占位符整数(%d||%i),浮点数(%f),对象(%o),字符(%s); 2.console.error输出错误化的语句 ...

  9. C 标准库基础 IO 操作总结

    其实输入与输出对于不管什么系统的设计都是异常重要的,比如设计 C 接口函数,首先要设计好输入参数.输出参数和返回值,接下来才能开始设计具体的实现过程.C 语言标准库提供的接口功能很有限,不像 Pyth ...

  10. jquery 设置占位符

    <script type="text/javascript">    $(document).ready(function(){       $('.inputfiel ...