经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
spring boot之SpringApplication 事件监听
来源:jb51  时间:2019/3/14 10:09:52  对本文有异议

spring application listener

在 spring 框架中,有多种事件, 这些时间会在不同的运行时刻发布,来通知监听者。本文仅仅介绍 SpringApplicationEvent 的事件的监听。

事件类型

EventType 发布时间
ApplicationContextInitializedEvent 在 SpringApplication正在启动, ApplicationContext 已经准备好了,ApplicationContextInitializers 被调用, bean definitions 被加载之前
ApplicationStartingEvent 在一次启动之前发布
ApplicationEnvironmentPreparedEvent 在 Environment 准备好之后,会有 context 去使用这一 Environment, 会在 context 创建之前发出
ApplicationPreparedEvent 会在 bean definitions 加载之后,refresh 之前发布
ApplicationStartedEvent context 更新之后,任何应用或命令行启动调用之前
ApplicationReadyEvent 任何应用或命令行启动调用之后发布,说明应用已经可以被请求了
ApplicationFailedEvent 启动发生有异常时发步

如何监听

监听器需要使用 org.springframework.context.ApplicationListener 这个接口的实例, 其声明如下:

  1. @FunctionalInterface
  2. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  3. /**
  4. * Handle an application event. * @param event the event to respond to
  5. */
  6. void onApplicationEvent(E event);
  7. }

需要使用 SpringApplication.addListeners(…​) 或 SpringApplicationBuilder.listeners(…​) 来添加监听器。也可以在 META-INF/spring.factories 文件中配置:org.springframework.context.ApplicationListener=com.example.project.MyListener。

例子:

  1. public class StartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
  2. @Override
  3. public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
  4. System.out.println("called own starting listener");
  5.  
  6. System.out.println(applicationStartingEvent.getClass());
  7. }
  8. }
  9.  
  1. @SpringBootApplication
  2. public class DemoApplication {
  3. public static void main(String[] args){
  4. SpringApplication application = new SpringApplication(DemoApplication.class);
  5. application.addListeners(new StartingEventListener());
  6. application.run(args);
  7. }
  8. }

终端运行 jar 包:

  1. $ java -jar build/libs/springlisteners-0.0.1-SNAPSHOT.jar
  2. called own starting listener
  3. class org.springframework.boot.context.event.ApplicationStartingEvent
  4.  
  5. . ____ _ __ _ _
  6. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  7. ' |____| .__|_| |_|_| |_\__, | / / / /
  8. =========|_|==============|___/=/_/_/_/
  9. :: Spring Boot :: (v2.1.3.RELEASE)

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号