上篇文章介绍实现ApplicationListener接口实现spring事件监听:
ApplicationListener--- Spring源码从入门到精通(二十九)
这篇文章介绍注解实现事件监听@EventListener,eventListener注解如何实现监听某个事件,然后源码里在调用上篇文章说的finishRefresh方法派发事件监听。本篇文章通过代码实例和源码分析来说明eventListener注解。
一、代码实例
自定义userService,方法上用@EventListener注解,指定需要监听的事件,可以数组的形式写多个,此处监听的是ApplicationEvent类。这样和实现applicationListener监听到的事件结果打印是相同的。
/**
* @author keying
*/
@Service
public class UserService {
@EventListener(classes = {ApplicationEvent.class})
public void listen(ApplicationEvent event) {
System.out.println("userService监听到的事件:" + event);
}
}
junit测试还是不变,为了方便大家阅读,贴一份出来:
@Test
public void test() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class);
applicationContext.publishEvent(new ApplicationEvent("自定义发布事件") {});
/* MyApplicationEvent myApplicationEvent = new MyApplicationEvent("123");
applicationContext.publishEvent(myApplicationEvent);*/
applicationContext.close();
}
二、源码原理
使用EventListenerMethodProcessor后置处理器来解析方法上的@EventListener。
Extends SmartInitializationSingleton原理:
这个afterSingletonsInstantiated是什么时候触发的呢?
ioc容器创建对象,refresh()。
finishBeanFactoryInitialization():初始化剩下的单实例bean。A、先创建所有的单实例bean,通过getBean()。B、获取所有单实例bean,判断是否是SmartInitializingSingleton,是就执行监听的afterSingletonsInstantiated方法。