先搭建源码分析环境,这里引用的是org.springframework4.3.12.RELEASE版本分析的,debug之前github上下载相关源码-地址 除了在上述代码中打上断点之外,增加EventListenerMethodProcessor的afterSingletonsInstantiated方法打上断点,AbstractApplicationContext的initApplicationEventMulticaster方法和registerListeners上打上断点。
@ComponentScan("com.atguigu.ext") @Configuration public class ExtConfig { @Bean public Blue blue(){ return new Blue(); } } @Component public class MyApplicationListener implements ApplicationListener<ApplicationEvent> { //当容器中发布此事件以后,方法触发 @Override public void onApplicationEvent(ApplicationEvent event) { // TODO Auto-generated method stub //断点 System.out.println("收到事件:"+event); } } @Service public class UserService { @EventListener(classes={ApplicationEvent.class}) public void listen(ApplicationEvent event){ //断点 System.out.println("UserService。。监听到的事件:"+event); } } <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> </dependencies> @Test public void test01(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(ExtConfig.class); //发布事件; //断点 applicationContext.publishEvent(new ApplicationEvent(new String("我发布的时间")) { }); applicationContext.close(); }开始debug,进入断点
查看调用栈发现有refresh中有专门初始化该事件多播器(派发器)的方法
代码向下走发现,当容器中没有applicationEventMulticaster对象时,这里new了一个事件多播器(派发器)对象
继续debug,F9,进入监听器注册方法 查看调用栈发现,这个方法时refresh中的专门监听器注册方法
继续debug,F9,进入SmartInitializingSingleton 的->afterSingletonsInstantiated()方法,主要是userservice的listen方法没有注册到事件多播器中,此方法完成这个操作。
继续F9 ,发现事件监听器监听到事件了
查看调用栈