Spring Boot 监听器概述
Spring Boot 监听器(Listeners)基于 Spring Framework 的事件机制(ApplicationEvent 和 ApplicationListener),用于在应用生命周期或自定义事件触发时执行特定逻辑。它们提供了一种松耦合的方式响应应用状态变化,常用于初始化资源、监控应用状态、执行异步任务等。
概念
事件类型
- 内置系统事件:
- ContextRefreshedEvent: ApplicationContext初始化或刷新时触发
- ContextStartedEvent: ApplicationContext启动后触发
- ContextStoppedEvent: ApplicationContext停止后触发
- ContextClosedEvent: ApplicationContext关闭后触发
- ApplicationStartedEvent: Spring Boot应用启动后触发
- ApplicationReadyEvent: 应用准备就绪时触发(推荐在此执行启动逻辑)
- ApplicationFailedEvent: 启动失败时触发
- 自定义事件: 继承ApplicationEvent创建特定业务事件
监听器类型
接口实现: 实现ApplicationListener
注解驱动: 使用@EventListener注解方法
SmartApplicationListener: 支持事件类型过滤和顺序控制
简单说就是:
- 事件(Event): 继承 ApplicationEvent 的类,表示一个事件(如应用启动、关闭等)。
- 监听器(Listener): 实现 ApplicationListener 接口、SmartApplicationListener接口或使用 @EventListener注解的组件,用于响应事件。
- 事件发布(Publisher): 通过 ApplicationEventPublisher 发布事件。
最佳使用场景
自定义事件
步骤1:定义事件类
public class OrderCreateEvent extends ApplicationEvent {
private String orderId;
public OrderCreateEvent(Object source, String orderId) {
super(source);
this.orderId = orderId;
}
public String getOrderId() {
return orderId;
}
}
步骤2:发布事件
@Service
public class OrderService {
@Autowired
private ApplicationEventPublisher eventPublisher;
public void createOrder(Order order) {
// 创建订单逻辑...
eventPublisher.publishEvent(new OrderCreateEvent(this, order.getId()));
}
}
事件监听
方式1:实现ApplicationListener接口
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
public class SystemStartupListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("=== 应用启动完成,执行初始化操作 ===");
// 初始化业务数据...
}
}
public class OrderCreateEventListener implements ApplicationListener<OrderCreateEvent> {
@Override
public void onApplicationEvent(OrderCreateEvent event) {
System.out.println("=== 执行操作 ===");
// 初始化业务数据...
}
}
方式2:使用@EventListener注解
import org.springframework.context.event.EventListener;
import org.springframework.boot.context.event.ApplicationStartedEvent;
@Component
public class AnnotationBasedListener {
@EventListener
public void handleStartedEvent(ApplicationStartedEvent event) {
System.out.println("=== 应用启动事件捕获 ===");
}
}
@Component
public class AnnotationBasedListener {
@EventListener
public void handleStartedEvent(OrderCreateEvent event) {
System.out.println("=== 执行操作 ===");
}
}
方式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 OrderCreateEvent) {
log.info("监听到 OrderCreateEvent...");
}
if (event instanceof MyEvent) {
log.info("监听到 MyEvent...");
MyEvent myEvent = (MyEvent) event;
System.out.println("时间:" + myEvent.getTime() + " 信息:" + myEvent.getMsg());
}
}
}
高级配置
监听器顺序控制
@EventListener
@Order(Ordered.HIGHEST_PRECEDENCE) // 最高优先级
public void handleOrderEvent(OrderCreateEvent event) {
System.out.println("收到订单创建事件,订单ID:" + event.getOrderId());
// 发送通知、更新统计...
}
异步事件处理
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.initialize();
return executor;
}
}
// 可进行如下替换
@EventListener
@Async
public void asyncHandleEvent(MyEvent event) {
// 异步执行
}
条件过滤
@EventListener(condition = "#event.orderId.startsWith('VIP')")
public void handleVipOrder(OrderCreateEvent event) {
// 只处理VIP订单
}