Spring ApplicationEvent 事件处理--不用引入中间件
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Configuration
public class EventConfiguration {
@Component
public static class MyEvent extends ApplicationEvent {
public MyEvent() {
super("My Event Source");
}
}
@Component
public static class MyEventPublisher {
private final ApplicationEventPublisher publisher;
public MyEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish() {
publisher.publishEvent(new MyEvent());
}
}
@Component
public static class MyEventHandler implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println("Event received: " + event.getSource());
}
}
// 使用 @EventListener 注解的方式处理事件
@Component
public static class EventListenerHandler {
@EventListener
public void handleEvent(MyEvent event) {
System.out.println("EventListener received: " + event.getSource());
}
}
}
这个代码示例展示了如何在Spring应用中定义和发布自定义事件,并使用ApplicationListener
接口和@EventListener
注解来处理这些事件。这是一个内置于Spring框架中的简单事件驱动机制,无需引入额外的中间件。
评论已关闭