文档章节

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

程序猿DD
 程序猿DD
发布于 03/09 07:17
字数 1244
阅读 961
收藏 10

今天继续来聊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 新特性详解正在连载,点击看看都有哪些解读

© 著作权归作者所有

共有 人打赏支持
程序猿DD
粉丝 348
博文 59
码字总数 80114
作品 0
闵行
[springboot]事件监听(三)

前言 spring boot在启动过程中增加事件监听机制,为用户功能拓展提供极大的便利。 支持的事件类型四种 ApplicationStartedEvent ApplicationEnvironmentPreparedEvent ApplicationPreparedE...

菜鸟腾飞
09/15
0
0
Spring Boot 2.0 新特性解读

点击上方“程序员小灰”,选择“置顶公众号” 有趣有内涵的文章第一时间送达! 本文转载自公众号 InfoQ 作者|翟永超编辑|郭蕾Spring Boot 2.0 来啦,有哪些新特性?升级吗?写在前面 北京时...

bjweimengshu
04/13
0
0
Spring Boot 2.0干货系列:(一)Spring Boot1.5X升级到2.0指南

前言 Spring Boot已经发布2.0有4个月多,多了很多新特性,一些坑也慢慢被填上,最近有空,就把本博客中Spring Boot干货系列对应的源码从1.5X升级到Spring Boot 2.0,顺便整理下升级的时候遇到...

嘟爷MD
07/24
0
0
【第2章 Spring快速入门】2.1 Java应用之HelloWorld

上一节:【第1章 Spring概述与结构】1.2 Spring模块与结构 注意:本系列教程不会通过工程单独依赖某个Jar包,而是通过开源中国的Maven库,来进行Jar包的依赖管理,所以后续的讲解都是以Maven...

陶邦仁
2015/05/24
0
3
SpringBoot启动流程详解

本文系转载,自己mark一下,加深记忆和理解。原文地址:http://zhaox.github.io/java/2016/03/22/spring-boot-start-flow 环境 本文基于Spring Boot版本1.3.3, 使用了spring-boot-starter-w...

如日之昇
08/21
0
0

没有更多内容

加载失败,请刷新页面

加载更多

八月新增开源项目:假装自己是图形界面的 Git 命令行工具

每月新增开源项目。顾名思义,每月更新一期。我们会从社区上个月新收录的开源项目中,挑选出有价值的、有用的、优秀的、或者好玩的开源项目来和大家分享。数量不多,但我们力求推荐的都是精品...

编辑部的故事
18分钟前
5
0
20180918 find命令与Linux文件扩展名

命令find 用来查找搜索文件。 搜索文件相关命令: which 从环境变量里的目录中去搜索 whereis(不常用) 从一个固定的库中搜索 locate(需要单独安装 yum install -y mlocate) 查询时会从/var/...

野雪球
20分钟前
1
0
GO 数组相关操作

package mainimport("fmt""math/rand""time")func main() {//数组的几种定义方式var arr1 [3]int = [3]int{1,2,3}var arr2 = [3]int{4,5,6}arr3 := [3]string{"h", "w", ......

汤汤圆圆
今天
1
0
JAVA 中interrupt、interrupted和isInterrupted的区别

首先,我们说明下三个方法的功能 interrupt() 向当前调用者线程发出中断信号 isinterrupted() 查看当前中断信号是true还是false interrupted() 是静态方法,查看返回当前中断信号并将中断信号...

我爱春天的毛毛雨
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部