在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()
方法時,就會觸發自定義事件的發布,并且事件監聽者會接收到事件并進行相應的處理。