1 定义事件
public class CustomEvent extends ApplicationContextEvent {
private Integer id;
private String message;
public CustomEvent(ApplicationContext source, Integer id, String message) {
super(source);
this.id = id;
this.message = message;
}
// getter/setter
}
2 定义事件监听器(实际调用的方法)
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
System.out.println("CustomEventListener.getSource() = " + event.getSource());
System.out.println("CustomEventListener.getId() = " + event.getId());
System.out.println("CustomEventListener.getMessage() = " + event.getMessage());
}
}
注册其他:refresh、closed(Spring 内部提供)
public class ContextRefreshEventListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("ContextRefreshedEvent = " + this.getClass().getName());
}
}
public class ContextClosedEventListener implements ApplicationListener<ContextClosedEvent> {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("ContextClosedEventListener = " + this.getClass().getName());
}
}
3 xml 中注册
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.zhang.custom_event.event.CustomEventListener"/>
<bean class="com.zhang.custom_event.event.ContextRefreshEventListener"/>
<bean class="com.zhang.custom_event.event.ContextClosedEventListener"/>
</beans>
4 调用
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
System.out.println("--------publishEvent CustomEvent---------");
applicationContext.publishEvent(new CustomEvent(applicationContext, 1, "success"));
System.out.println("--------registerShutdownHook---------");
applicationContext.registerShutdownHook();
}
输出如下
ContextRefreshedEvent = com.zhang.custom_event.event.ContextRefreshEventListener
--------publishEvent CustomEvent---------
CustomEventListener.getSource() = org.springframework.context.support.ClassPathXmlApplicationContext@2d8e6db6, started on Tue Nov 22 16:00:52 CST 2022
CustomEventListener.getId() = 1
CustomEventListener.getMessage() = success
--------registerShutdownHook---------
ContextClosedEventListener = com.zhang.custom_event.event.ContextClosedEventListener
流程
refresh → finishRefresh → publishEvent → multicastEvent
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) { // <----- 不同类型的事件
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
通过继承 AbstractApplicationEventMulticaster 的 SimpleApplicationEventMulticaster 进行事件发布(遍历循环)