热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

SpringBootApplication事件监听的实现方案

这篇文章主要介绍了SpringBootApplication事件监听的实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

先说结论

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 {

  @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 {

  @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 {

  @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 {

  @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 {

  @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 {

  @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> 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

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


推荐阅读
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • PyCharm下载与安装指南
    本文详细介绍如何从官方渠道下载并安装PyCharm集成开发环境(IDE),涵盖Windows、macOS和Linux系统,同时提供详细的安装步骤及配置建议。 ... [详细]
  • PHP 5.2.5 安装与配置指南
    本文详细介绍了 PHP 5.2.5 的安装和配置步骤,帮助开发者解决常见的环境配置问题,特别是上传图片时遇到的错误。通过本教程,您可以顺利搭建并优化 PHP 运行环境。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 扫描线三巨头 hdu1928hdu 1255  hdu 1542 [POJ 1151]
    学习链接:http:blog.csdn.netlwt36articledetails48908031学习扫描线主要学习的是一种扫描的思想,后期可以求解很 ... [详细]
  • This document outlines the recommended naming conventions for HTML attributes in Fast Components, focusing on readability and consistency with existing standards. ... [详细]
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 解决微信电脑版无法刷朋友圈问题:使用安卓远程投屏方案
    在工作期间想要浏览微信和朋友圈却不太方便?虽然微信电脑版目前不支持直接刷朋友圈,但通过远程投屏技术,可以轻松实现在电脑上操作安卓设备的功能。 ... [详细]
  • 网络运维工程师负责确保企业IT基础设施的稳定运行,保障业务连续性和数据安全。他们需要具备多种技能,包括搭建和维护网络环境、监控系统性能、处理突发事件等。本文将探讨网络运维工程师的职业前景及其平均薪酬水平。 ... [详细]
  • 本文详细介绍了如何在ECharts中使用线性渐变色,通过echarts.graphic.LinearGradient方法实现。文章不仅提供了完整的代码示例,还解释了各个参数的具体含义及其应用场景。 ... [详细]
  • 本文介绍如何在Linux服务器之间使用SCP命令进行文件传输。SCP(Secure Copy Protocol)是一种基于SSH的安全文件传输协议,支持从远程机器复制文件到本地服务器或反之。示例包括从192.168.45.147复制tomcat目录到本地/home路径。 ... [详细]
  • 解决JAX-WS动态客户端工厂弃用问题并迁移到XFire
    在处理Java项目中的JAR包冲突时,我们遇到了JaxWsDynamicClientFactory被弃用的问题,并成功将其迁移到org.codehaus.xfire.client。本文详细介绍了这一过程及解决方案。 ... [详细]
author-avatar
小荷蛋蛋图_945
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有