[关闭]
@zhuanxu 2017-11-27T06:26:41.000000Z 字数 1595 阅读 2607

Spring boot 事件监听

spring-boot


事件的作用是为bean和bean之间的通信提供支持。spring中定义事件的流程:

而配置监听器的方式有4种:

下面具体分析下第3,第4种方法的实现。

DelegatingApplicationListener

这个类主要负责加载context.listener.classes中的事件监听器。
在 SpringApplication 启动的时候,会通过下面的语句setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));去加载监听器,监听器在META-INF/spring.factories中设置,其中就有DelegatingApplicationListener

spring-boot
下面我们去看DelegatingApplicationListener.onApplicationEvent方法。

  1. public void onApplicationEvent(ApplicationEvent event) {
  2. if (event instanceof ApplicationEnvironmentPreparedEvent) {
  3. List<ApplicationListener<ApplicationEvent>> delegates = getListeners(
  4. ((ApplicationEnvironmentPreparedEvent) event).getEnvironment());
  5. if (delegates.isEmpty()) {
  6. return;
  7. }
  8. this.multicaster = new SimpleApplicationEventMulticaster();
  9. for (ApplicationListener<ApplicationEvent> listener : delegates) {
  10. this.multicaster.addApplicationListener(listener);
  11. }
  12. }
  13. }

只处理ApplicationEnvironmentPreparedEvent事件,并且去读key为private static final String PROPERTY_NAME = "context.listener.classes";的值。

EnvironmentPostProcessor

EnvironmentPostProcessor实现了SmartInitializingSingleton接口,当单例bean初始化完后会调用afterSingletonsInstantiated方法,里面关键的方法是:

  1. annotatedMethods = MethodIntrospector.selectMethods(targetType,
  2. new MethodIntrospector.MetadataLookup<EventListener>() {
  3. @Override
  4. public EventListener inspect(Method method) {
  5. return AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class);
  6. }
  7. });

寻找bean中被EventListener注解的方法,最后调用applicationContext.addApplicationListener的方法添加监听器。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注