Spring Boot监听机制
大约 2 分钟Spring BootSpring Boot
概述
监听由三部分组成:事件、监听器、广播器组成。
系统内置监听器
- 广播器核心类为
ApplicationEventMulticaster
,主要由三个方法:添加监听器、移除监听器、广播事件 - 系统监听器类:
ApplicationListener
- 事件类:
ApplicationEvent
Spring Boot内置了很多的系统事件,关乎应用启动各个节点,其类图如下:
- ApplicationStartingEvent: run方法首次启动时立即调用
- ApplicationEnvironmentPreparedEvent: 环境准备之后 创建Appplicationcontex之前
- ApplicationContextInitializedEvent: 创建applicationContext之后 未加载任何bean之前
- ApplicationPreparedEvent: 在应用程序上下文已加载但尚未刷新之前调用
- ApplicationStartedEvent: 上下文已刷新应用程序已启动但尚未调用 未调用applicationRunner和CommandLineRunner
- ApplicationReadyEvent: 调用所有CommandLineRunner和applicationRunner之后
- ApplicationFailedEvent: 异常错误时
各事件在Spring Boot启动的执行顺序如下:
初始化
内置监听器的初始化与系统初始化器过程类似,都是读取spring.factories
配置文件实现,关键代码如下:
发布实现
在EventPublishingRunListener
类中有对应用启动各阶段事件广播的逻辑。以启动事件为例,广播器会发布ApplicationStartingEvent
事件。
自定义监听器
1. 自定义监听应用准备事件
@Order(1)
@Component
public class CustomeApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("application is ready");
}
}
效果如下:
2. 自定义事件监听
声明事件:
public class TestEvent extends ApplicationEvent {
private String message;
public String getMessage() {
return message;
}
public TestEvent(Object source, String message) {
super(source);
this.message = message;
}
}
声明监听:
@Component
public class TestListener implements ApplicationListener<TestEvent> {
@Override
public void onApplicationEvent(TestEvent event) {
System.out.println("message =" + event.getMessage());
}
}
发布事件:
@SpringBootApplication
public class XwSbdemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(XwSbdemoApplication.class, args);
applicationContext.publishEvent(new TestEvent("","HELLO WORLD"));
}
}
总结
- 实现
ApplicationListener
或者SmartApplicationListener
接口可实现自定义监听器,SmartApplicationListener
可以同时监听多个事件,ApplicationListener
只能监听一个事件。 - 事件监听默认是同步执行,如果需要异步执行可以通过
@Async
实现