org.springframework.context.ApplicationListener 是 Spring 事件机制中的核心接口,用于监听并处理 Spring 容器发布的事件(ApplicationEvent)。它体现了 Spring 的 事件驱动模型 和 观察者模式。
一、基本作用
ApplicationListener 用于:
监听 Spring 容器中的特定事件,并在事件发生时执行相应的逻辑
接口定义(简化):
@FunctionalInterface
public interface ApplicationListener
extends EventListener {
void onApplicationEvent(E event);
}
• 当 Spring 发布一个事件时
• 所有监听该事件的 ApplicationListener 都会被回调
• 在 onApplicationEvent 中执行自定义逻辑
二、Spring 中事件驱动的意义
1️⃣ 解耦组件之间的直接调用
传统方式(紧耦合):
orderService.createOrder();
emailService.sendEmail();
smsService.sendSms();
事件驱动方式(解耦):
orderService.publishOrderCreatedEvent();
监听者各自处理:
• 发送邮件
• 发送短信
• 记录日志
• 更新统计
✅ 发布者不需要知道谁在监听
2️⃣ 支持 Spring 生命周期管理
Spring 自身大量使用事件来通知容器状态变化,例如:
事件 含义
ContextRefreshedEvent 容器初始化或刷新完成
ContextStartedEvent 容器启动
ContextStoppedEvent 容器停止
ContextClosedEvent 容器关闭
RequestHandledEvent HTTP 请求处理完成(Web)
你可以监听这些事件,在 应用启动完成 / 关闭前 执行逻辑。
三、典型使用场景
1️⃣ 监听 Spring 容器启动完成
@Component
public class StartupListener
implements ApplicationListener {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("Spring 容器启动完成");
}
}
✅ 常用于:
• 缓存预热
• 初始化配置
• 启动后台任务
2️⃣ 监听自定义业务事件
定义事件
public class OrderCreatedEvent extends ApplicationEvent {
private final String orderId;
public OrderCreatedEvent(Object source, String orderId) {
super(source);
this.orderId = orderId;
}
}
发布事件
applicationEventPublisher.publishEvent(
new OrderCreatedEvent(this, "123")
);
监听事件
@Component
public class OrderListener
implements ApplicationListener {
@Override
public void onApplicationEvent(OrderCreatedEvent event) {
System.out.println("订单创建:" + event.getOrderId());
}
}
四、与 @EventListener 的对比
特性 ApplicationListener @EventListener
实现方式 接口 注解
泛型支持 ✅ ✅
代码侵入性 较高 低
推荐程度 Spring 内部 ✅ 业务代码推荐
✅ 现代 Spring 项目更推荐使用 @EventListener
五、底层原理(简要)
-
Spring 容器维护一个事件广播器 ApplicationEventMulticaster
-
发布事件时:
• 找到所有匹配的 ApplicationListener
• 依次同步(或异步)调用 onApplicationEvent
-
支持:
• 泛型事件匹配
• 异步事件(@Async)
• 事件继承体系
六、总结一句话
ApplicationListener 是 Spring 事件机制的核心接口,用于监听容器或业务事件,实现组件解耦、生命周期管理和事件驱动架构。
如果你愿意,我也可以:
• 对比 ApplicationListener 与消息队列(MQ)
• 分析事件传播顺序
• 讲 Spring Boot 中的实战用法
• 分析异步事件的坑(事务、线程)