Spring源码-ApplicationListener基于事件的订阅者发布者模式

如何使用

spring容器自身提供了基于事件的订阅者发布者模式,即ApplicationListener,它能支持一些系统事件具体见ApplicationEvent的子类,同时也支持我们自定义事件使用方法如下

容器自身的事件,如:ApplicationContextEvent,我们想获取一个全局变量ApplicationContext(代码仅供参考)

1
2
3
4
5
6
7
8
9
10
11
12
@Component
public class ContextRefreshAppliationListener implements ApplicationListener<ApplicationContextEvent> {

public static ApplicationContextEvent applicationContext;

//触发 application.pulish(new ContextRefreshedEvent())
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//容器启动后在某些节点会发送事件,我们只需要实现onApplicationEvent即可。
applicationContext=event.getApplicationContext();
}
}

自定义事件:

  1. 定义事件,事件继承自ApplicationEvent
  2. 实现该事件的AppliationListener
  3. 在程序某个时间点触发applicationContext.publishEvent方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class CoustomEvent extends ApplicationEvent {
private String name;
private String eventType;
private String summary;

public CoustomEvent(Object source, String name, String eventType, String summary) {
this(source);
this.name = name;
this.eventType = eventType;
this.summary = summary;
}

public CoustomEvent(Object source) {
super(source);
}
}

@Component
public class CoustomAppliationListener implements ApplicationListener<CoustomEvent> {

//触发 application.pulish(new ContextRefreshedEvent())
@Override
public void onApplicationEvent(CoustomEvent event) {
System.out.println(event.getName() + " eventType:" + event.getEventType() + " summary:" + event.getSummary() + " in time:" + event.getTimestamp());
}
}

//触发
applicationContext.publishEvent(new CoustomEvent("source","liuhao","sendEmail"," dest liu67224657@qq.com"));

原理

tbd