1.创建本地事件和事件监听器
/**
* 事件类
*/
public class MyEventA extends ApplicationEvent {
private static final long serialVersionUID = 1L;
public MyEventA(Object source) {
super(source);
System.out.println("MyEventA 构造方法被执行了...");
}
public void out(String name){
System.out.println("MyEventA .... out方法执行了"+name);
}
}
/**
* 监听器
*/
public class MyListenerA implements ApplicationListener<MyEventA> {
@Override
public void onApplicationEvent(MyEventA event) {
System.out.println("======MyListenerA 监听器触发了...");
// 执行事件中的特定方法
event.out("AAAAA");
}
}
2 触发发送事件
public class TestListenerController {
@Autowired
private ApplicationContext mApplicationContext;
@GetMapping("/testlistener")
public String testPublishEvent(){
System.out.println("====>get");
mApplicationContext.publishEvent(new MyEventA(new Object()));
return "";
}
}
3 添加注册器到spring.factories
![](https://img-blog.csdnimg.cn/img_convert/58721e49c66745947edb61a68f685598.png)
图1
4 项目启动时候会将listener 实例化到内存中
走到SpringApplication的构造方法中,会走到getSpringFactoriesInstances方法中,实例化listener类型的类,通过setListeners方法保存在内存中
![](https://img-blog.csdnimg.cn/img_convert/09bd7eeddac04f7564db95d1ce63c8d9.png)
图2
![](https://img-blog.csdnimg.cn/img_convert/823e46dd01b9fd817f0bd35f4ddf9437.png)
图3
5. 执行Controller方法
http://localhost:8081/testlistener
会执行mApplicationContext.publishEvent(new MyEventA(new Object()));
![](https://img-blog.csdnimg.cn/img_convert/bce9f9846ee8d675a9363949cd39d19b.png)
图4
执行到SimpleApplicationEventMulticaster类中的multicastEvent
![](https://img-blog.csdnimg.cn/img_convert/870efbfb3b4b21e41b1a36b63f931dcf.png)
图5
执行SimpleApplicationEventMulticaster父类AbstractApplicationEventMulticaster中的getApplicationListeners方法找到匹配的listener,在执行到retrieveApplicationListeners方法
![](https://img-blog.csdnimg.cn/img_convert/c481e29e8c20035504a5d6e8babb818f.png)
图6
![](https://img-blog.csdnimg.cn/img_convert/7df2e602907246490a5b37710e2f0558.png)
图7
执行GenericApplicationListenerAdapter类中supportsEventType方法
declaredEventType.isAssignableFrom(eventType))将需要监听的对象和发送的事件对象匹配,匹配成功将此listener,也就是之前声明的MyListenerA实例化对象,添加到发送列表
![](https://img-blog.csdnimg.cn/img_convert/0e2b3c5ef593ddefe99efe9b650d7073.png)
图8
最后执行图5中的invokeListener(listener, event),将事件发送到对应的监听器
综上流程可以看出,spring的事件发送接收是一种观察者模式,即注册监听模式,当应用启动的时候,根据spring.factories文件,将监听器实例化后保存在内存中,到有触发动作是,根据发送的事件类型,从所有初始化的监听器中找到匹配的监听器,在发送事件对象