SpringBoot - 事件机制使用详解(ApplicationEvent、ApplicationListener)
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
// 自定义事件
public class MyCustomEvent extends ApplicationEvent {
public MyCustomEvent(Object source) {
super(source);
}
}
// 自定义监听器
@Configuration
public class MyCustomListener implements ApplicationListener<MyCustomEvent> {
@Override
public void onApplicationEvent(MyCustomEvent event) {
// 处理事件逻辑
System.out.println("MyCustomListener received MyCustomEvent: " + event);
}
}
// 触发事件的地方
@Configuration
public class EventPublisher {
private final ApplicationEventPublisher publisher;
public EventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}
public void publish() {
MyCustomEvent event = new MyCustomEvent(this);
publisher.publishEvent(event);
}
}
// 在SpringBoot启动完成后发布事件
@Configuration
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
private final EventPublisher eventPublisher;
public StartupListener(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
// 发布事件
eventPublisher.publish();
}
}
}
这个代码示例展示了如何在SpringBoot应用中定义、监听和发布自定义事件。MyCustomEvent
是一个自定义事件类,MyCustomListener
是监听该事件的监听器。EventPublisher
类中的publish
方法用于发布事件,而StartupListener
则在SpringBoot启动完成后发布事件。这个例子有助于理解Spring的事件机制,并在实际应用中进行事件驱动的开发。
评论已关闭