服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

spring boot之SpringApplication 事件监听

2019-06-24 23:06posuoren JAVA教程

这篇文章主要介绍了spring boot之SpringApplication 事件监听,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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 这个接口的实例, 其声明如下:

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

需要使用 SpringApplication.addListeners(…