- 从企业级开发到云原生微服务:Spring Boot实战
- 汪云飞等
- 339字
- 2025-02-17 20:16:14
3.5 Bean之间的事件通信
如果Bean之间需要通信,比如说BeanA完成了处理后需要告知BeanB,通知BeanB继续处理,那么我们称BeanA为Publisher,称BeanB为Listener。
Publisher和Listener之间传递的事件数据通过继承ApplicationEvent来实现。
Publisher的实现方式如下。
◎通过ApplicationEventPublisherAware注入ApplicationEventPublisher发布事件,前面已演示。
◎直接注入ApplicationEventPublisher发布事件。
◎直接注入ApplicationContext发布事件。
Listener的实现方式如下。
◎实现ApplicationListener接口。
◎注解@EventListener的方法接收事件。
事件数据:

发布者:


监听者:

a.EventListenerService实现了ApplicationListener<MessageEvent>接口,泛型MessageEvent可缩小监听事件的范围,通过覆写onApplicationEvent方法来监听事件。
监听者还可以注解@EventListener方法来监听事件。

推荐使用@EventListener注解方式,耦合度更低。
除能监听自定义发布的事件外,还可以监听系统发布的事件,示例如下。

主要的系统事件如下。
◎ContextRefreshedEvent:当ApplicationContext被初始化或刷新时发布该事件。
◎ContextStartedEvent:当ApplicationContext开始时发布该事件。
◎ContextStoppedEvent:当ApplicationContext停止时发布该事件。
◎ContextClosedEvent:当ApplicationContext关闭时发布该事件。