【SpringBoot3】Spring Boot Event 自定义事件的发布与监听
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
// 自定义事件
class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) {
super(source);
}
}
// 自定义事件监听器
@Component
class CustomEventListener {
@EventListener
public void onCustomEvent(CustomEvent event) {
// 处理事件逻辑
System.out.println("Custom event received: " + event.getSource());
}
}
// 事件发布者
@Component
class EventPublisher {
private final ApplicationEventPublisher publisher;
public EventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish() {
CustomEvent event = new CustomEvent("Hello, World!");
publisher.publishEvent(event);
}
}
这个代码示例展示了如何在Spring Boot应用中创建和发布自定义事件,以及如何编写一个监听器来处理这些事件。CustomEvent
类继承自ApplicationEvent
,用于封装事件的数据。CustomEventListener
类中的onCustomEvent
方法通过@EventListener
注解标记为事件监听器,并处理接收到的自定义事件。EventPublisher
组件使用ApplicationEventPublisher
发布CustomEvent
事件。
评论已关闭