ApplicationEvent 是 Spring 框架中事件驱动编程模型的核心组件,用于实现应用程序内部的事件发布-订阅机制。
ApplicationEvent 是 Spring 框架中事件驱动编程模型的核心组件,用于实现应用程序内部的事件发布-订阅机制。
一、ApplicationEvent 是什么?
ApplicationEvent 是 Spring 的事件抽象类,属于观察者模式在 Spring 中的实现,主要特点包括:
- 事件源:事件的产生者
- 事件对象:继承 ApplicationEvent 的具体事件类
- 监听器:实现 ApplicationListener 或使用 @EventListener
- 发布器:ApplicationEventPublisher
二、基本使用方式
1️⃣自定义事件
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
private String message;
public MyEvent(Object source,String message) {
super(source);
this.message = message;
}
public String getMessage(){
return this.message;
}
2️⃣发布事件
@Service
@RequiredArgsConstructor
public class EventPublisherService {
private final ApplicationEventPublisher applicationEventPublisher;
//@Scheduled(fixedDelay = 10 * 1000) 定时测试发布可删
public void publishEvent() {
MyEvent hello = new MyEvent(this, "hello");
applicationEventPublisher.publishEvent(hello);
}
}
3️⃣监听
@Component
public class MyListener {
@EventListener
public void handleMyCustomEvent(MyEvent myEvent) {
System.out.println(myEvent.getMessage());
}
}