Spring Boot 2.0 新特性(二):新增事件ApplicationStartedEvent

今天继续来聊Spring Boot 2.0的新特性。本文将具体说说2.0版本中的事件模型,尤其是新增的事件:ApplicationStartedEvent

原文首发:http://blog.didispace.com/Spring-Boot-2-0-feature-2-ApplicationStartedEvent/

在Spring Boot 2.0中对事件模型做了一些增强,主要就是增加了ApplicationStartedEvent事件,所以在2.0版本中所有的事件按执行的先后顺序如下:

  • ApplicationStartingEvent
  • ApplicationEnvironmentPreparedEvent
  • ApplicationPreparedEvent
  • ApplicationStartedEvent <= 新增的事件
  • ApplicationReadyEvent
  • ApplicationFailedEvent

从上面的列表中,我们可以看到ApplicationStartedEvent位于ApplicationPreparedEvent之后,ApplicationReadyEvent之前。

下面我们通过代码的方式来直观的感受这个事件的切入位置,以便与将来我们在这个切入点加入自己需要的逻辑。

第一步:我们可以编写ApplicationPreparedEventApplicationStartedEvent以及ApplicationReadyEvent三个事件的监听器,然后在这三个事件触发的时候打印一些日志来观察它们各自的切入点,比如:

@Slf4j
public class ApplicationPreparedEventListener implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        log.info("......ApplicationPreparedEvent......");
    }

}

@Slf4j
public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info("......ApplicationStartedEvent......");
    }

}

@Slf4j
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("......ApplicationReadyEvent......");
    }

}

第二步:在/src/main/resources/目录下新建:META-INF/spring.factories配置文件,通过配置org.springframework.context.ApplicationListener来加载上面我们编写的监听器。

org.springframework.context.ApplicationListener=
  com.didispace.ApplicationPreparedEventListener,\
  com.didispace.ApplicationReadyEventListener,\
  com.didispace.ApplicationStartedEventListener

此时,我们运行Spring Boot应用可以获得类似如下日志输出:

2018-03-07 18:15:18.591  INFO 83387 --- [           main] com.didispace.Application                : Starting Application on zhaiyongchaodeMacBook-Pro.local with PID 83387 (/Users/zhaiyongchao/Documents/git/github/SpringBoot-Learning/Chapter1-2-1/target/classes started by zhaiyongchao in /Users/zhaiyongchao/Documents/git/github/SpringBoot-Learning/Chapter1-2-1)
2018-03-07 18:15:18.591  INFO 83387 --- [           main] com.didispace.Application                : No active profile set, falling back to default profiles: default
2018-03-07 18:15:18.658  INFO 83387 --- [           main] c.d.ApplicationPreparedEventListener     : ......ApplicationPreparedEvent......
2018-03-07 18:15:18.662  INFO 83387 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@20d3d15a: startup date [Wed Mar 07 18:15:18 CST 2018]; root of context hierarchy
2018-03-07 18:15:19.879  INFO 83387 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-03-07 18:15:19.926  INFO 83387 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-03-07 18:15:19.930  INFO 83387 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-03-07 18:15:19.946  INFO 83387 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/zhaiyongchao/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-03-07 18:15:20.068  INFO 83387 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-03-07 18:15:20.068  INFO 83387 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1410 ms
2018-03-07 18:15:20.210  INFO 83387 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-03-07 18:15:20.214  INFO 83387 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-03-07 18:15:20.214  INFO 83387 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-03-07 18:15:20.214  INFO 83387 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-03-07 18:15:20.215  INFO 83387 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-03-07 18:15:20.513  INFO 83387 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@20d3d15a: startup date [Wed Mar 07 18:15:18 CST 2018]; root of context hierarchy
2018-03-07 18:15:20.592  INFO 83387 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-03-07 18:15:20.593  INFO 83387 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-03-07 18:15:20.623  INFO 83387 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-07 18:15:20.623  INFO 83387 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-07 18:15:20.660  INFO 83387 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-03-07 18:15:20.787  INFO 83387 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-03-07 18:15:20.839  INFO 83387 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-03-07 18:15:20.843  INFO 83387 --- [           main] com.didispace.Application                : Started Application in 2.866 seconds (JVM running for 3.337)
2018-03-07 18:15:20.845  INFO 83387 --- [           main] c.d.ApplicationStartedEventListener      : ......ApplicationStartedEvent......
2018-03-07 18:15:20.847  INFO 83387 --- [           main] c.d.ApplicationReadyEventListener        : ......ApplicationReadyEvent......

从日志中我们可以看到清晰的看到ApplicationPreparedEventApplicationStartedEvent以及ApplicationReadyEvent三个事件的切入点。通过这个例子可能读者会感到疑问:ApplicationStartedEventApplicationReadyEvent从事件命名和日志输出位置来看,都是应用加载完成之后的事件,它们是否有什么区别呢?

下面可以看看官方文档对ApplicationStartedEventApplicationReadyEvent的解释:

An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.An ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests

从文档中我们可以知道他们两中间还有一个过程就是command-line runners被调用的内容。所以,为了更准确的感受这两个事件的区别,我们在应用主类中加入CommandLineRunner的实现,比如:

@Slf4j
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public DataLoader dataLoader() {
        return new DataLoader();
    }

    @Slf4j
    static class DataLoader implements CommandLineRunner {

        @Override
        public void run(String... strings) throws Exception {
            log.info("Loading data...");
        }
    }

}

最后,我们再运行程序,此时我们可以发现这两个事件中间输出了上面定义的DataLoader的输出内容,具体如下:

2018-03-07 18:15:20.845  INFO 83387 --- [main] c.d.ApplicationStartedEventListener      : ......ApplicationStartedEvent......
2018-03-07 18:15:20.846  INFO 83387 --- [main] com.didispace.Application$DataLoader     : Loading data...
2018-03-07 18:15:20.847  INFO 83387 --- [main] c.d.ApplicationReadyEventListener        : ......ApplicationReadyEvent......

代码示例

本文的相关例子可以查看下面仓库中的Chapter1-2-1目录:

Spring Booot 2.0 新特性详解正在连载,点击看看都有哪些解读

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容