Application Events and Listeners

总有需要在系统启动期间做一些操作的场景,比如在服务启动后去读数据库获取配置信息等操作,使用事件监听是个不错的选择
@SpringBootApplication
public class Application {
public static void main(String[] args) {

    SpringApplication springApplication = new SpringApplication(Application.class);
    springApplication.addListeners(new Listen());
    springApplication.run(args);

}

}

public class Listen implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("listen");
}
}

Application events are sent in the following order, as your application runs:

An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.
An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known but before the context is created.
An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.
An ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called.
An ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.
An ApplicationFailedEvent is sent if there is an exception on startup.

更多配置参见:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-events-and-listeners

你可能感兴趣的:(Application Events and Listeners)