在Spring中,可以使用Spring的事件机制来实现发布订阅模式。
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 publishEvent(String message) {
CustomEvent customEvent = new CustomEvent(this, message);
applicationEventPublisher.publishEvent(customEvent);
}
}
@Component
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
String message = event.getMessage();
// 处理事件逻辑
}
}
@Autowired
private CustomEventPublisher customEventPublisher;
public void doSomething() {
customEventPublisher.publishEvent("Some message");
}
这样,当调用doSomething()
方法时,就会触发自定义事件的发布,并且事件监听者会接收到事件并进行相应的处理。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Spring依赖注入有哪些优势