SpringBoot Application事件监听的实现方案

先说结论

SpringBoot Application共支持6种事件监听,按顺序分别是:

  1. ApplicationStartingEvent:在Spring最开始启动的时候触发
  2. ApplicationEnvironmentPreparedEvent:在Spring已经准备好上下文但是上下文尚未创建的时候触发
  3. ApplicationPreparedEvent:在Bean定义加载之后、刷新上下文之前触发
  4. ApplicationStartedEvent:在刷新上下文之后、调用application命令之前触发
  5. ApplicationReadyEvent:在调用applicaiton命令之后触发
  6. ApplicationFailedEvent:在启动Spring发生异常时触发

另外:

  • ApplicationRunner和CommandLineRunner的执行在第五步和第六步之间
  • Bean的创建在第三步和第四步之间
  • 在启动类中,执行SpringApplication.run()方法后的代码,会在第六步后执行

再上代码:

ApplicationStartingEvent

public class ApplicationStartingEventListener implements ApplicationListener<ApplicationStartingEvent> {

  @Override
  public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
    System.out.println("============>>>>> applicationStartingEvent is trigged");
    System.out.println(applicationStartingEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

ApplicationEnvironmentPreparedEvent

public class ApplicationEnvironmentPreparedEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

  @Override
  public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
    System.out.println("============>>>>> ApplicationEnvironmentPreparedEvent is trigged");
    System.out.println(applicationEnvironmentPreparedEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

ApplicationPreparedEvent

public class ApplicationPreparedEventListener implements ApplicationListener<ApplicationPreparedEvent> {

  @Override
  public void onApplicationEvent(ApplicationPreparedEvent applicationPreparedEvent) {
    System.out.println("============>>>>> applicationPreparedEvent is trigged");
    System.out.println(applicationPreparedEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

ApplicationStartedEvent

public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> {

  @Override
  public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
    System.out.println("============>>>>> applicationStartedEvent is trigged");
    System.out.println(applicationStartedEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

ApplicationReadyEvent

public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

  @Override
  public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
    System.out.println("============>>>>> applicationReadyEvent is trigged");
    System.out.println(applicationReadyEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

ApplicationFailedEvent

public class ApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> {

  @Override
  public void onApplicationEvent(ApplicationFailedEvent applicationFailedEvent) {
    System.out.println("============>>>>> ApplicationFailedEvent is trigged");
    System.out.println(applicationFailedEvent.getTimestamp());
    System.out.println("============>>>>> End");
  }
}

主启动类

@SpringBootApplication
public class SpringBootTestApplication {

  public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(SpringBootTestApplication.class);
    springApplication.addListeners(new ApplicationEnvironmentPreparedEventListener());
    springApplication.addListeners(new ApplicationFailedEventListener());
    springApplication.addListeners(new ApplicationPreparedEventListener());
    springApplication.addListeners(new ApplicationReadyEventListener());
    springApplication.addListeners(new ApplicationStartedEventListener());
    springApplication.addListeners(new ApplicationStartingEventListener());
    springApplication.run(args);
  }
}

运行结果

Connected to the target VM, address: '127.0.0.1:62927', transport: 'socket'
============>>>>> applicationStartingEvent is trigged
============>>>>> End
============>>>>> ApplicationEnvironmentPreparedEvent is trigged
============>>>>> End

 .  ____     _      __ _ _
 /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/ ___)| |_)| | | | | || (_| | ) ) ) )
 ' |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::    (v2.0.3.RELEASE)

2018-11-01 14:52:35.117 INFO 2044 --- [      main] c.l.s.b.test.SpringBootTestApplication  : Starting SpringBootTestApplication on EDIANZU-ETGVGB5 with PID 2044 (D:\Code\SelfCode\SpringCloud\Test\SpringBootTest\target\classes started by Administrator in D:\Code\SelfCode\SpringCloud)
2018-11-01 14:52:35.122 INFO 2044 --- [      main] c.l.s.b.test.SpringBootTestApplication  : No active profile set, falling back to default profiles: default
============>>>>> applicationPreparedEvent is trigged
============>>>>> End
2018-11-01 14:52:35.212 INFO 2044 --- [      main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3406472c: startup date [Thu Nov 01 14:52:35 CST 2018]; root of context hierarchy
2018-11-01 14:52:36.891 INFO 2044 --- [      main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-11-01 14:52:36.920 INFO 2044 --- [      main] o.apache.catalina.core.StandardService  : Starting service [Tomcat]
2018-11-01 14:52:36.920 INFO 2044 --- [      main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.31
2018-11-01 14:52:36.925 INFO 2044 --- [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: [D:\Program Files\Java\jdk1.8.0_191\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\ThinkPad\Bluetooth Software\;C:\Program Files\ThinkPad\Bluetooth Software\syswow64;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;D:\Program Files\Java\jdk1.8.0_191\bin;D:\Program Files\Git\cmd;D:\Program Files\apache-maven-3.5.4\bin;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;.]
2018-11-01 14:52:37.048 INFO 2044 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]    : Initializing Spring embedded WebApplicationContext
2018-11-01 14:52:37.048 INFO 2044 --- [ost-startStop-1] o.s.web.context.ContextLoader      : Root WebApplicationContext: initialization completed in 1841 ms
2018-11-01 14:52:37.377 INFO 2044 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-01 14:52:37.389 INFO 2044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-01 14:52:37.390 INFO 2044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-01 14:52:37.390 INFO 2044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-01 14:52:37.390 INFO 2044 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-01 14:52:37.598 INFO 2044 --- [      main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-01 14:52:37.857 INFO 2044 --- [      main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3406472c: startup date [Thu Nov 01 14:52:35 CST 2018]; root of context hierarchy
2018-11-01 14:52:37.922 INFO 2044 --- [      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-11-01 14:52:37.923 INFO 2044 --- [      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-11-01 14:52:37.973 INFO 2044 --- [      main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-01 14:52:37.973 INFO 2044 --- [      main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-01 14:52:38.160 INFO 2044 --- [      main] o.s.j.e.a.AnnotationMBeanExporter    : Registering beans for JMX exposure on startup
2018-11-01 14:52:38.206 INFO 2044 --- [      main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-01 14:52:38.212 INFO 2044 --- [      main] c.l.s.b.test.SpringBootTestApplication  : Started SpringBootTestApplication in 3.976 seconds (JVM running for 5.088)
============>>>>> applicationStartedEvent is trigged
============>>>>> End
============>>>>> applicationReadyEvent is trigged
============>>>>> End

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2019-05-28

springboot 事件监听的实现方法

定义事件 @Getter public class TestEvent extends ApplicationEvent { private String msg; public TestEvent(Object source, String msg) { super(source); this.msg = msg; } } 定义事件监听(注解方式) @Component public class TestListen { @EventListener public void testListe

spring boot之SpringApplication 事件监听

spring application listener 在 spring 框架中,有多种事件, 这些时间会在不同的运行时刻发布,来通知监听者.本文仅仅介绍 SpringApplicationEvent 的事件的监听. 事件类型 EventType 发布时间 ApplicationContextInitializedEvent 在 SpringApplication正在启动, ApplicationContext 已经准备好了,ApplicationContextInitializers 被调用,

浅谈Spring-boot事件监听

springboot的事件监听:为bean之间的消息通信提供支持.当一个bean做完一件事以后,通知另一个bean知晓并做出相应处理.这时,我们需要另一个bean,监听当前bean所发生的事件. 实现步骤:四个步骤,四种方式 第一种方式 1.自定义事件,一般是继承ApplicationEvent抽象类 2.定义事件监听器,一般是实现ApplicationListener接口 3.1)把监听器加入到SpringApplication中:ApplicationListener.addListener

Spring Boot应用事件监听示例详解

前言 本文主要给大家介绍了关于Spring Boot应用事件监听的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧 1. Spring Boot特有的应用事件 除了Spring框架的事件,Spring Boot的SpringApplication也发送了一些自己的事件: ApplicationStartingEvent:在任何处理(除了注册listener和initializer)开始之前发送. ApplicationEnvironmentPreparedEvent: 在

微信小程序 实现拖拽事件监听实例详解

微信小程序 拖拽监听功能: 在软件开发或者 APP应用开发的时候,经常会遇到拖拽监听,最近自己学习微信小程序的知识,就想实现这样的拖拽效果,这里就记录下. 需要做个浮在scroll-view之上的button.尝试了一下. 上GIF: Android中也会有类似移动控件的操作.思路差不多.获取到位移的X Y 的变量,给控件设置坐标. 1.index.wxml ../images/gundong.png" bindtap="ballClickEvent" style="

Spring Boot企业常用的starter示例详解

SpringBoot简介# Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. Spring Boot让我们的Spring应用变的更轻量化.比如:你可以仅仅依靠一个Java类来运行一个Spring引用.你也可以打包你的应用为

Spring Boot LocalDateTime格式化处理的示例详解

JDK8的新特性中Time API,其包括Clock.Duration.Instant.LocalDate.LocalTime.LocalDateTime.ZonedDateTime,在这里就不一一介绍了,相信很多人都会使用其代替Date及Calendar来处理日期时间,下面介绍Spring Boot处理LocalDateTime格式. Controller接收LocalDateTime参数 在Spring中,接收LocalDateTime日期时间数据时,只需要使用@DateTimeFormat

如何在spring boot中进行参数校验示例详解

上文我们讨论了spring-boot如何去获取前端传递过来的参数,那传递过来总不能直接使用,需要对这些参数进行校验,符合程序的要求才会进行下一步的处理,所以本篇文章我们主要讨论spring-boot中如何进行参数校验. lombok使用介绍 在介绍参数校验之前,先来了解一下lombok的使用,因为在接下来的实例中或有不少的对象创建,但是又不想写那么多的getter和setter,所以先介绍一下这个很强大的工具的使用. Lombok 是一个可以通过简单的注解形式来帮助我们简化消除一些必须有但显得很

spring boot微服务自定义starter原理详解

这篇文章主要介绍了spring boot微服务自定义starter原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用spring boot开发微服务后,工程的数量大大增加(一定要按照领域来切,不要一个中间件客户端包一个),让各个jar从开发和运行时自包含成了一个重要的内容之一.spring boot starter就可以用来解决该问题(没事启动时别依赖于applicationContext.getBean获取bean进行处理,依赖关系

Spring boot注解@Async线程池实例详解

这篇文章主要介绍了Spring boot注解@Async线程池实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 从Spring3开始提供了@Async注解,该注解可以被标注在方法上,以便异步地调用该方法.调用者将在调用时立即返回,方法的实际执行将提交给Spring TaskExecutor的任务中,由指定的线程池中的线程执行. 1. TaskExecutor Spring异步线程池的接口类,其实质是java.util.concurrent

Spring Boot读取resources目录文件方法详解

这篇文章主要介绍了Spring Boot读取resources目录文件方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在Java编码过程中,我们常常希望读取项目内的配置文件,按照Maven的习惯,这些文件一般放在项目的src/main/resources下,因此,合同协议PDF模板.Excel格式的统计报表等模板的存放位置是resources/template/test.pdf,下面提供两种读取方式,它们分别在windows和Linux

spring boot中的properties参数配置详解

application.properties application.properties是spring boot默认的配置文件,spring boot默认会在以下两个路径搜索并加载这个文件 src\main\resources src\main\resources\config 配置系统参数 在application.properties中可配置一些系统参数,spring boot会自动加载这个参数到相应的功能,如下 #端口,默认为8080 server.port=80 #访问路径,默认为/

spring boot application properties配置实例代码详解

废话不多说了,直接给大家贴代码了,具体代码如下所示: # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # ========