Spring Boot监听器
约 540 字大约 2 分钟
2025-07-04
概述
Spring Boot 监听器(Listeners)基于 Spring Framework 的事件机制(ApplicationEvent 和 ApplicationListener),用于在应用生命周期或自定义事件触发时执行特定逻辑。
它们提供了一种松耦合的方式响应应用状态变化,常用于初始化资源、监控应用状态、执行异步任务等。
事件类型
| 类型 | 触发时机 |
|---|---|
| ContextRefreshedEvent | ApplicationContext初始化或刷新时触发 |
| ContextStartedEvent | ApplicationContext启动后触发 |
| ContextStoppedEvent | ApplicationContext停止后触发 |
| ContextClosedEvent | ApplicationContext关闭后触发 |
| ApplicationStartedEvent | Spring Boot应用启动后触发 |
| ApplicationReadyEvent | 应用准备就绪时触发(推荐在此执行启动逻辑) |
| ApplicationFailedEvent | 启动失败时触发 |
自定义事件
- 事件(Event):继承ApplicationEvent,表示一个事件
- 监听器(Listener): 实现ApplicationListener接口、SmartApplicationListener接口或使用@EventListener注解的组件,用户响应事件
- 事件发布(Publisjer):通过ApplicationEventPublisher发布事件
第一步:自定义事件类
public class TestSpringBootListenerEvent extent ApplicationEvent{
private String filed;
// 忽略getter、setter、constructor
}第二步:发布事件
@Service
public class TestSpringBootListenerPublish {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void createOrder(Order order) {
// 创建订单逻辑...
eventPublisher.publishEvent(new TestSpringBootListenerEvent("test data"));
}
}第三步:监听事件
方式1: 时间ApplicationListener接口
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
public class SpringBootTestListener implements ApplicationListener<TestSpringBootListenerEvent> {
@Override
public void onApplicationEvent(TestSpringBootListenerEvent event) {
System.out.println(event.getField());
// 其他业务操作
}
}方式2:使用@EventListener注解
@Component
public class AnnotationBasedListener {
@EventListener
public void handleStartedEvent(TestSpringBootListenerEvent event) {
System.out.println("=== 执行操作 ===");
}
}其他可用注解:
// 指定优先级
@Order(Ordered.HIGHEST_PRECEDENCE)
// 条件过滤 只处理VIP开头的orderId
@EventListener(condition = "#event.orderId.startsWith('VIP')")方式3:实现SmartApplicationListener接口
@Slf4j
@Component
public class MyTask implements SmartApplicationListener {
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return eventType == MyEvent.class || eventType == OrderCreateEvent.class;
}
@Override
public int getOrder() {
return 0;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof TestSpringBootListenerEvent) {
log.info("监听到 TestSpringBootListenerEvent...");
}
if (event instanceof MyEvent) {
log.info("监听到 MyEvent...");
MyEvent myEvent = (MyEvent) event;
System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());
}
}
}SmartApplicationListener接口的其他方法说明:
- supportsEventType: 确认当前监听器是否支持当前时间类型
- supportSourceType: 确认当前监听器是否实际支持给定的原类型
- getOrder: 优先级,数值越小,优先级越高
- getListenerId: 返回监听器的可选标识符