ApplicationEventPubish是干啥用的。
看到publish相比大家都能想到发布订阅模式吧。没错ApplicationEventPubish就是用来实现着中功能的。
ApplicationEventPubish发布了一个事件,监听这个事件的并作出相应的处理。
那为啥需要监听着呢,可以发布了直接去执行相应的逻辑呀。这是因为可拔插化思想。我订阅了这个事件,我可
以定制他的处理方式,甚至可以不处理,等以后来扩展,这就是它的优势。
主要涉及了三个类
ApplicationEventPublisher 发布事件
@Service
public class PublisherService {
@Autowired
private ApplicationEventPublisher publisher;
public void sendMessage(){
publisher.publishEvent(new MyEvent(this,"小王","爱旅游"));
}
}
ApplicationEvent 定义事件
public class MyEvent extends ApplicationEvent {
private String name;
private String act;
public MyEvent(Object source,String name, String act) {
super(source);
this.name = name;
this.act = act;
}
}
ApplicationListener 监听事件
@Component
public class EventListener implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
System.out.println("监听器开始执行---》");
System.out.println("我是"+event.getName()+"我再"+event.getAct());
}
@org.springframework.context.event.EventListener
public void register(MyEvent event){
System.out.println("监听器二开始执行---》");
System.out.println("我是"+event.getName()+"我也再"+event.getAct());
}
}
参考文献
springIOC源码接口分析(七):ApplicationEventPublisher
soul 网关入门篇(四):ApplicationEventPublisher 的使用