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

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

(0)

相关推荐

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

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

  • 浅谈Spring-boot事件监听

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

  • 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 被调用,

  • SpringBoot Application事件监听的实现方案

    先说结论 SpringBoot Application共支持6种事件监听,按顺序分别是: ApplicationStartingEvent:在Spring最开始启动的时候触发 ApplicationEnvironmentPreparedEvent:在Spring已经准备好上下文但是上下文尚未创建的时候触发 ApplicationPreparedEvent:在Bean定义加载之后.刷新上下文之前触发 ApplicationStartedEvent:在刷新上下文之后.调用application命令之

  • SpringBoot ApplicationListener事件监听接口使用问题探究

    终日惶惶,不知归路:一日写起代码,突发奇想,若是在运行时发现自定义上下文的数据丢失,我们该如何解决处理数据丢失的问题? 问题复现一下,大家看下面的代码,观察是否有问题,又该如何解决这个问题: @RequestMapping("verify") @RestController @DependsOn({"DingAppInfoService","CloudChatAppInfoService"}) public class LoginAction {

  • SpringBoot利用切面注解及反射实现事件监听功能

    目录 前言 效果图 监听原理 核心源码 源码地址 前言 当某个事件需要被监听的时候,我们需要去做其他的事前,最简单的方式就是将自己的业务 方法追加到该事件之后. 但是当有N多个这样的需求的时候我们都这样一个个去添加修改事件的源码吗? 这篇文章将告诉你如何用一个注解,就可以将你的业务代码通过切面的方式添加到事件的前后,而不需要修改事件的代码 效果图 如下图所示,add方法内并没有调用其他的方法,但是其他方法仍然被执行了. 只要给监听方法加@AddEventListener()注解就可以让它在事件前

  • Spring事件监听机制观察者模式详解

    目录 前言 观察者模式 观察者的角色定义 Java中的事件机制 Spring中的事件机制 Spring事件监听案例 小结 前言 Spring中提供了一套默认的事件监听机制,在容器初始化时便使用了这套机制.同时,Spring也提供了事件监听机制的接口扩展能力,开发者基于此可快速实现自定义的事件监听功能. Spring的事件监听机制是在JDK事件监听的基础上进行的扩展,也是在典型观察者模式上的进一步抽象和改进.所以,结合Spring的事件监听机制与观察者模式来学习,可以达到理论与实践的完美融合. 本

  • js事件监听机制(事件捕获)总结

    在前端开发过程中我们经常会遇到给页面元素添加事件的问题,添加事件的js方法也很多,有直接加到页面结构上的,有使用一些js事件监听的方法,由于各个浏览器对事件冒泡事件监听的机制不同,le浏览器只有事件冒泡,没有事件监听的机制,对于事件监听的兼容性问题是最大的难题: 1.直接把事件的方法写在页面结构上 function eventfun(){ //console.log(this); } <input type="button" onclick="eventfun()&qu

  • Spring的事件监听机制示例详解

    前言 最近公司在重构广告系统,其中核心的打包功由广告系统调用,即对apk打包的调用和打包完成之后的回调,需要提供相应的接口给广告系统.因此,为了将apk打包的核心流程和对接广告系统的业务解耦,利用了spring的事件监听特性来满足需求.以下说明spring的事件机制的相关内容. 首先spring事件分为事件发布者(EventPublisher).事件监听者(EventListener),还包括一个事件广播者(这个是spring实现相关,这一节不讨论).使用spring事件机制,需要自定义事件发布

  • 基于 jQuery 实现键盘事件监听控件

    最近项目里要做一个画板,需要对键盘事件进行监听,来进行诸如撤回.重做.移动.缩放等操作,因此顺手实现了一个键盘事件监听控件,期间略有收获,整理出来,希望对大家有所帮助,更希望能获得高手的指点. 1. 自动获取焦点 似乎浏览器的键盘事件只能被那些可以获得焦点的元素设置监听,而通常需要监听事件的 <DIV>.<CANVAS> 元素都不能获得焦点,因此需要修改目标元素的某些属性使其可以获得焦点,另外一种可行的方法是将事件委托给诸如 <INPUT> 标签.这里采用的是第一类方法

随机推荐