SpringBoot Event 事件监听
概述
ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。事件监听的作用与消息队列有一点类似。
事件监听的结构
主要有三个部分组成:
- 发布者
- 事件
- 监听者
相关类及继承关系类图
UML类图🔗
 {
super(source);
this.user = user;
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XbqtqPLO-1626962037544)(evernotecid://5017348F-AB9A-4431-A7FF-4D27C619FCD9/appyinxiangcom/31661346/ENResource/p226)]
发布者
事件发布是由ApplicationContext对象管控的,我们发布事件前需要注入ApplicationContext对象调用publishEvent方法完成事件发布。
·ApplicationEventPublisher applicationEventPublisher
虽然声明的是ApplicationEventPublisher,但是实际注入的是applicationContext
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
ApplicationContext applicationContext;
@Autowired
ApplicationEventPublisher applicationEventPublisher;
@GetMapping("testEvent")
public void test() {
applicationEventPublisher.publishEvent(new MyTestEvent("dzf-casfd-111", new User("dzf-625096527-111", "xiaoming", 19)));
applicationContext.publishEvent(new MyTestEvent("dzf-49687489-111", new User("dzf-625096527-111", "xiaowang", 20)));
}
}
监听者
面向接口编程,实现ApplicationListener接口
@Component
public class MyTestListener implements ApplicationListener<MyTestEvent> {
@Override
public void onApplicationEvent(MyTestEvent myTestEvent) {
System.out.println("MyTestListener : " + myTestEvent.getUser());
}
}
使用@EventListener注解配置
@Component
public class MyTestListener2{
@EventListener(MyTestEvent.class)
public void onApplicationEvent(MyTestEvent myTestEvent) {
System.out.println("MyTestListener2:" + myTestEvent.getUser());
}
}