org.springframework.context.ApplicationListener

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

五、底层原理(简要)

  1. Spring 容器维护一个事件广播器 ApplicationEventMulticaster

  2. 发布事件时:

    • 找到所有匹配的 ApplicationListener

    • 依次同步(或异步)调用 onApplicationEvent

  3. 支持:

    • 泛型事件匹配

    • 异步事件(@Async)

    • 事件继承体系

六、总结一句话

ApplicationListener 是 Spring 事件机制的核心接口,用于监听容器或业务事件,实现组件解耦、生命周期管理和事件驱动架构。

如果你愿意,我也可以:

• 对比 ApplicationListener 与消息队列(MQ)

• 分析事件传播顺序

• 讲 Spring Boot 中的实战用法

• 分析异步事件的坑(事务、线程)

相关推荐
七夜zippoe2 天前
Agent 网关设计:统一入口、智能路由与负载均衡
运维·ai·log4j·负载均衡·agent·网关设计
汤姆宝库7 天前
推理时计算深拆:思维链、验证搜索与测试时Scaling
log4j
神一样的老师14 天前
WS63 嵌入式 SSD1306 OLED 驱动单元测试实战
单元测试·log4j
silvamux_16 天前
大模型 API 单元测试怎么 mock 不误伤
单元测试·log4j·php
system_error_x17 天前
自动化常规代码辅助系统
运维·自动化·log4j
看浪的路人17 天前
第10讲:大模型应用测试——从单元测试到 E2E 评测的完整体系
log4j
草莓熊Lotso19 天前
【C++ 基于微服务的即时通讯系统】基建三件套:gflags + gtest + spdlog 源码编译安装与实战入门
linux·网络·数据库·c++·微服务·log4j
j7~20 天前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
楚楚25121 天前
2026最新6款Cursor平替AI编程工具深度实测对比
log4j