spring boot在启动过程中提供了一些事件的监听,这样极大的方便了开发者拓展功能;
spring boot支持的事件类型:
关键步骤:
1、实现接口ApplicationListener来创建自己的事件监听类;如:
@Component
public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartingEvent> {
@Override
public void onApplicationEvent(ApplicationStartingEvent applicationStartedEvent) {
System.out.println("application starting .....");
}
}
2、在启动类中注册,修改此前启动类的代码为:
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
springApplication.addListeners(new ApplicationStartedEventListener());
springApplication.run(args);
}
}
3、运行发现启动前先打印
image.png
同样的,为了省事,直接用lamda来实现其他几个接口
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
springApplication.addListeners(new ApplicationStartedEventListener());
springApplication.addListeners((ApplicationListener<ApplicationPreparedEvent>) event -> {
System.out.println("application prepared event");
});
springApplication.addListeners((ApplicationListener<ApplicationReadyEvent>) event -> {
System.out.println("application ready event");
});
springApplication.run(args);
}
}
系统启动时,执行顺序为:application starting
> application prepared
> application ready
网友评论