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 新特性詳解正在連載,點擊看看都有哪些解讀

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章