Spring The Boot container performs specific operations when loaded. of recommends

  • 2021-01-06 00:33:22
  • OfStack

In some cases we need to do something after the Spring container has been started and loaded, in which case we can implement ApplicationListener < E extends ApplicationEvent > Interface and specify events to perform operations, such as starting some custom daemon threads

ApplicationContextEvent is the base class for events raised by ApplicationContext, which has several implementation classes:

ContextRefreshedEvent: This event is emitted when the ApplicationContext container is initialized or refreshed. This event is executed once
ContextStartedEvent: This event is emitted when the ApplicationContext container is started using the start() method of the ConfigurableApplicationContext interface
ContextClosedEvent: This event is emitted when the ApplicationContext container is closed using the close() method of the ConfigurableApplicationContext interface
ContextStopedEvent: This event is emitted when the ApplicationContext container is stopped using the stop() method of the ConfigurableApplicationContext interface

The code example


@Component
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
 @Override
 public void onApplicationEvent(ContextRefreshedEvent event) {
  System.out.println(" This event is emitted when the container is initialized or refreshed , perform 1 time ");
 }
}

conclusion


Related articles: