@zhuanxu
2017-11-27T06:26:41.000000Z
字数 1595
阅读 3033
spring-boot
事件的作用是为bean和bean之间的通信提供支持。spring中定义事件的流程:
而配置监听器的方式有4种:
下面具体分析下第3,第4种方法的实现。
这个类主要负责加载context.listener.classes中的事件监听器。
在 SpringApplication 启动的时候,会通过下面的语句setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));去加载监听器,监听器在META-INF/spring.factories中设置,其中就有DelegatingApplicationListener。
下面我们去看DelegatingApplicationListener.onApplicationEvent方法。
public void onApplicationEvent(ApplicationEvent event) {if (event instanceof ApplicationEnvironmentPreparedEvent) {List<ApplicationListener<ApplicationEvent>> delegates = getListeners(((ApplicationEnvironmentPreparedEvent) event).getEnvironment());if (delegates.isEmpty()) {return;}this.multicaster = new SimpleApplicationEventMulticaster();for (ApplicationListener<ApplicationEvent> listener : delegates) {this.multicaster.addApplicationListener(listener);}}}
只处理ApplicationEnvironmentPreparedEvent事件,并且去读key为private static final String PROPERTY_NAME = "context.listener.classes";的值。
EnvironmentPostProcessor实现了SmartInitializingSingleton接口,当单例bean初始化完后会调用afterSingletonsInstantiated方法,里面关键的方法是:
annotatedMethods = MethodIntrospector.selectMethods(targetType,new MethodIntrospector.MetadataLookup<EventListener>() {@Overridepublic EventListener inspect(Method method) {return AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class);}});
寻找bean中被EventListener注解的方法,最后调用applicationContext.addApplicationListener的方法添加监听器。
