SpringApplication Event Monitoring for spring boot

  • 2021-07-06 10:52:24
  • OfStack

spring application listener

In the spring framework, there are multiple events that are released at different runtime times to notify listeners. This article only introduces the listening of SpringApplicationEvent events.

Event type

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

How to listen

The listener requires an instance of the interface org. springframework. context. ApplicationListener, which is declared as follows:


@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 (...) or SpringApplicationBuilder. listeners (...) is required to add listeners. It can also be configured in the META-INF/spring. factories file: org. springframework. ApplicationListener = com. example. project. MyListener.

Examples:


public class StartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
 @Override
 public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
  System.out.println("called own starting listener");

  System.out.println(applicationStartingEvent.getClass());
 }
}


@SpringBootApplication
public class DemoApplication {
 public static void main(String[] args){
  SpringApplication application = new SpringApplication(DemoApplication.class);
  application.addListeners(new StartingEventListener());
  application.run(args);
 }
}

The terminal runs the jar package:


$ java -jar build/libs/springlisteners-0.0.1-SNAPSHOT.jar
called own starting listener
class org.springframework.boot.context.event.ApplicationStartingEvent

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

Related articles: