利用 Spring 中的事件监听机制也可以轻松实现观察者模式,观察目标也不需要维护观察者列表了,相当于发布-订阅模式,它们之间是完全解耦的,但每个观察者需要创建一个 Bean。
观察者配置代码:
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class ObserverConfiguration {
@Bean
public XmanEventListener readerListener1() {
return new XmanEventListener("1");
}
@Bean
public XmanEventListener readerListener2() {
return new XmanEventListener("2");
}
@Bean
public XmanEventListener readerListener3() {
return new XmanEventListener("3");
}
}
监听类
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationListener;
@RequiredArgsConstructor
public class XmanEventListener implements ApplicationListener<XmanEvent> {
@NonNull
private String name;
private String article;
@Override
public void onApplicationEvent(XmanEvent event) {
// 更新
updateArticle(event);
}
private void updateArticle(XmanEvent event) {
this.article = (String) event.getSource();
System.out.printf("我是:%s,事件更新为:%s\n", this.name, this.article);
}
}
自定义事件类
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
@Getter
public class XmanEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public XmanEvent(Object source) {
super(source);
}
}