Spring Boot框架强大的事件驱动模型(ApplicationEvent)
在Spring Boot中,你可以通过扩展ApplicationEvent
类来创建自定义事件,并通过实现ApplicationEventPublisherAware
接口或者直接使用@Autowired
注入ApplicationEventPublisher
来发布这些事件。
以下是一个简单的例子,演示如何创建和发布自定义事件:
- 定义自定义事件类:
public class CustomEvent extends ApplicationEvent {
private String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
- 发布自定义事件:
@Component
public class CustomEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishCustomEvent(String message) {
CustomEvent customEvent = new CustomEvent(this, message);
applicationEventPublisher.publishEvent(customEvent);
}
}
- 监听自定义事件:
@Component
public class CustomEventListener {
@EventListener
public void handleCustomEvent(CustomEvent event) {
System.out.println("Received CustomEvent: " + event.getMessage());
}
}
当你调用publishCustomEvent
方法时,CustomEventListener
中的handleCustomEvent
方法会被触发,并打印出接收到的消息。
评论已关闭