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

图1
4 项目启动时候会将listener 实例化到内存中
走到SpringApplication的构造方法中,会走到getSpringFactoriesInstances方法中,实例化listener类型的类,通过setListeners方法保存在内存中

图2

图3
5. 执行Controller方法
http://localhost:8081/testlistener
会执行mApplicationContext.publishEvent(new MyEventA(new Object()));

图4
执行到SimpleApplicationEventMulticaster类中的multicastEvent

图5
执行SimpleApplicationEventMulticaster父类AbstractApplicationEventMulticaster中的getApplicationListeners方法找到匹配的listener,在执行到retrieveApplicationListeners方法

图6

图7
执行GenericApplicationListenerAdapter类中supportsEventType方法
declaredEventType.isAssignableFrom(eventType))将需要监听的对象和发送的事件对象匹配,匹配成功将此listener,也就是之前声明的MyListenerA实例化对象,添加到发送列表

图8
最好执行图5中的invokeListener(listener, event),将事件发送到对应的监听器
综上流程可以看出,spring的事件发送接收是一种观察者模式,即注册监听模式,当应用启动的时候,根据spring.factories文件,将监听器实例化后保存在内存中,到有触发动作是,根据发送的事件类型,从所有初始化的监听器中找到匹配的监听器,在发送事件对象
转载:https://blog.csdn.net/dalong3976/article/details/128688319