当前位置: 首页 > news >正文

ApplicationEventPublisher用法-笔记

1.ApplicationEventPublisher简介

org.springframework.context.ApplicationEventPublisher 是 Spring 框架中用于发布自定义事件的核心接口。它允许你在 Spring 应用上下文中触发事件,并由其他组件(监听器)进行响应。

ApplicationEventPublisher相关的核心概念

  1. 事件(Event):需要发布的自定义事件,继承 ApplicationEvent
  2. 监听器(Listener):通过 @EventListener 注解或实现 ApplicationListener 接口来接收事件。
  3. 发布者(Publisher):通过 ApplicationEventPublisher 接口的 publishEvent 方法触发事件。

2.用法介绍

2.1 常见用法步骤

  1. 定义自定义事件类
    继承 ApplicationEvent,并添加必要的属性。

  2. 创建事件监听器
    使用 @EventListener 注解或实现 ApplicationListener 接口。

  3. 在需要发布事件的类中注入 ApplicationEventPublisher
    通过 @Autowired 或构造函数注入,然后调用 publishEvent 方法。

2.2 代码示例

step1. 定义自定义事件
import lombok.Getter;
import org.springframework.context.ApplicationEvent;@Getter
public class UserRegisteredEvent extends ApplicationEvent {private final String email;private final String sourceName;public UserRegisteredEvent(String sourceName, String email) {super(sourceName);this.sourceName = sourceName;this.email = email;}}
step2. 创建事件监听器
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;@Component
public class EmailSenderListener {@EventListenerpublic void sendWelcomeEmail(UserRegisteredEvent event) {System.out.println(event.getSourceName() + " 发送欢迎邮件到:" + event.getEmail());}
}
step3. 发布事件的类
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;@Service
public class UserService2 {// 通过 @Autowired 方法注入 publisher@Autowiredprivate ApplicationEventPublisher publisher;public void registerUser(String email) {System.out.println("用户注册成功:" + email);// 发布事件publisher.publishEvent(new UserRegisteredEvent("UserService2", email));}
}
step4. 使用
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;@ComponentScan //扫描组件
public class TestMain {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(TestMain.class);UserService2 userService2 = context.getBean(UserService2.class);userService2.registerUser("user2@example.com");}
}

运行main函数,EmailSenderListener会监听到 UserRegisteredEvent 事件,并输出消息:

2.3 关键点说明

  1. 依赖注入
    在 UserService 中通过构造函数注入 ApplicationEventPublisher,这是 Spring 的推荐方式。publisher对应传入的bean是ApplicationContext,它是ApplicationEventPublisher的实现。

  2. 事件监听
    监听器通过 @EventListener 注解标记方法,参数类型必须与事件类匹配。

  3. 事件传递
    ApplicationEventPublisher.publishEvent 方法会将事件广播给所有监听器。

  4. 异步支持
    如果需要异步处理事件,可以在监听器方法上添加 @Async 注解,并启用异步支持(@EnableAsync)。

2.4 注意事项

  • 监听器必须是 Spring 管理的 Bean:通过 @Component@Service 等注解标记。
  • 事件类型匹配:监听器方法的参数类型必须与事件类完全一致。
  • 性能优化:频繁触发的事件可能导致性能问题,需合理设计。

通过这种方式,可以轻松实现在 Spring 应用中解耦组件之间的通信,符合观察者模式的设计理念。

相关文章:

  • 深入解析select与poll函数:原理、区别及实战案例
  • 文档编辑:reStructuredText全面使用指南 — 第四部分 高级主题
  • Python图像处理——基于Retinex算法的低光照图像增强系统
  • 【CF】Day43——Codeforces Round 906 (Div. 2) E1
  • 软件编程命名规范
  • 一种双模式机器人辅助股骨干骨折钢板植入方法
  • 【蓝桥杯】P12165 [蓝桥杯 2025 省 C/Java A] 最短距离
  • 量子威胁下的安全革命:后量子密码学技术路线与迁移挑战全解析
  • 三维天地智能路径规划引擎:以算法驱动,重新定义智能路径优化技术
  • 17.ArkUI Slider的介绍和使用
  • 数据库MySQL学习——day4(更多查询操作与更新数据)
  • 深入解析YOLO v1:实时目标检测的开山之作
  • Python命名参数的使用
  • 2024-08-12-20T10:00:00+0800什么格式?
  • 根据JSON动态生成表单表格
  • Jenkins流水线管理工具
  • Axure疑难杂症:详解设置选中与选中效果(玩转选中)
  • python——异常
  • 计算机视觉各类任务评价指标详解
  • 从FP32到BF16,再到混合精度的全景解析
  • 淮安四韵·名城新章: 网络名人领略“运河之都”魅力
  • 俄外长与美国务卿通电话,讨论俄美关系及乌克兰问题
  • 恒瑞医药赴港上市获证监会备案,拟发行不超8.15亿股
  • 王文涛会见德国汽车工业协会主席穆勒
  • 银川市长信箱被指乱回复:问诗词大会、答工程欠款,官方称工作失误
  • 伊朗最大港口爆炸:26公里外都能听到,超七百人受伤,原因指向化学品储存