Spring 事件发布机制@EventListener源码深度解析

迈不过友情╰ 2022-11-04 11:15 565阅读 0赞

  基于最新Spring 5.x,详细介绍了Spring @EventListener事件发布机制的实现原理!主要是initApplicationEventMulticaster从初始化事件广播器,registerListeners、ApplicationListenerDetector注册事件监听器,EventListenerMethodProcessor解析@EventListener注解,publishEvent发布事件。

  前文中,我们学习了Spring提供的事件发布机制:Spring 5.x 学习(8)—@EventListener事件发布机制应用详解,可用于实现一般性的业务解耦,在学习源码之前,一定要学会使用。现在我们简单的来看看Spring的事件发布机制的原理和源码,我们仅仅讲解Spring Framework中核心事件相关类,Spring Boot和Spring Cloud扩展了很多事件的实现,后面有机会再说!

文章目录

  • 1 initApplicationEventMulticaster初始化事件广播器
  • 2 registerListeners注册事件监听器
  • 3 ApplicationListenerDetector注册事件监听器
  • 4 EventListenerMethodProcessor解析@EventListener注解
    • 4.1 selectInvocableMethod查找可调用方法
  • 5 publishEvent发布事件
    • 5.1 multicastEvent广播事件
      • 5.1.1 getApplicationListeners获取监听器
        • 5.1.1.1 retriever.getApplicationListeners缓存获取监听器
      • 5.1.2 invokeListener调用监听器
        • 5.1.2.1 onApplicationEvent
  • 6 总结

1 initApplicationEventMulticaster初始化事件广播器

  Spring提供了ApplicationEventPublisher接口来表示应用程序事件发布者,用于发布自定义事件。实际上,我们的ApplicationContext上下文容器就是一个ApplicationEventPublisher的实现类,因此在项目很正宗可以直接通过ApplicationContext#publishEvent方法来发布事件。
  实际上,在ApplicationContext#publishEvent方法的实现代码中,事件的发布是通过委托一个ApplicationEventMulticaster对象——应用事件广播器,来实现的,该广播器内部保存的所有的事件监听器,用于真正的进行ApplicationContext事件广播,这么做的原因是为了实现类的职责解耦。但是在对外情况下,使用者是不知情的(他们认为仍然是ApplicationContext来发布的事件)!
  在IOC容器初始化过程中的initApplicationEventMulticaster方法就是用于初始化一个应用事件广播器,它是在普通Bean实例化和初始化之前执行的。和MessageSource的初始化过程一样,如果用户自定义了应用事件广播器,那么使用用户自定义的,否则默认使用SimpleApplicationEventMulticaster作为应用事件广播器。
在这里插入图片描述

  initApplicationEventMulticaster方法的源码很简单,如果存在名为applicationEventMulticaster的ApplicationEventMulticaster类型的bean定义,那么使用实例化该bean定义并作为,事件广播器,否则使用一个SimpleApplicationEventMulticaster实例作为广播器。由于事件广播器受到Spring管理,因此我们也可以在其他bean中引入该对象!

  1. /*AbstractApplicationContext的属性*/
  2. /**
  3. * 硬编码指定的beanFactory中的自定义ApplicationEventMulticaster 的beanName
  4. * 如果未提供自定义的广播器,则使用默认的SimpleApplicationEventMulticaster
  5. */
  6. public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
  7. /**
  8. * 保存事件发布中使用的帮助器类
  9. */
  10. @Nullable
  11. private ApplicationEventMulticaster applicationEventMulticaster;
  12. /**
  13. 1. AbstractApplicationContext的方法
  14. 2. <p>
  15. 3. 初始化应用程序事件广播器。 如果自己没有指定广播器,则使用SimpleApplicationEventMulticaster。
  16. */
  17. protected void initApplicationEventMulticaster() {
  18. //获取beanFactory
  19. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  20. /*
  21. * 本地工厂(忽略父工厂),如果包含名为"applicationEventMulticaster"的bean定义
  22. */
  23. if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
  24. //那么将该beanName的bean定义作为ApplicationEventMulticaster类型尝试初始化并赋给applicationEventMulticaster属性
  25. this.applicationEventMulticaster =
  26. beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
  27. if (logger.isTraceEnabled()) {
  28. logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
  29. }
  30. }
  31. /*
  32. * 否则,使用SimpleApplicationEventMulticaster实例作为广播器
  33. */
  34. else {
  35. //新建一个SimpleApplicationEventMulticaster实例,赋给applicationEventMulticaster属性
  36. this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
  37. //将初始化的广播器手动注册为一个名为"applicationEventMulticaster"的单例bean实例,因此我们在Spring管理的bean中也可以引入该对象
  38. beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
  39. if (logger.isTraceEnabled()) {
  40. logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
  41. "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
  42. }
  43. }
  44. }

  应用事件广播器的功能也很直白,就是进行应用程序事件广播。当产生某一个应用程序事件的时候,ApplicationContext会将该事件委托到广播器调用multicastEvent方法来发布,就像一个广播一样通知广播器内部保存的所有监听器,遍历并对每一个监听器调用listener.onApplicationEvent方法传递该事件,而后续的事件处理则是由每一个监听器自己的内部逻辑决定的。

2 registerListeners注册事件监听器

  registerListeners方法用于实例化并注册所有的Listener,即监听器。 监听器的来源有两个:

  1. 一个是调用addApplicationListener方法手动添加的listener实例,它们被添加到AbstractApplicationContext的applicationListeners集合中。
  2. 另一个就是从beanFactory中查找的ApplicationListener类型的bean定义的beanName,包括非单例的bean定义、FactoryBean本身以及Factory创建的Bean,但是不会初始化对应的bean实例,也不会初始化FactoryBean本身以及Factory创建的Bean,这是为了能让后处理器去对这这些bean进行处理。

  注册所有监听器之后会通过multicastEvent方法发布所有的早期的应用程序事件,非web应用默认没有早期事件。

  1. /**
  2. * AbstractApplicationContext的方法
  3. * <p>
  4. * 实例化并注册监听器到应用事件广播器中,随后发布早期应用程序事件
  5. */
  6. protected void registerListeners() {
  7. /*
  8. * 首先注册手动添加的监听器
  9. * 手动添加就是调用addApplicationListener方法添加的listener,它们此前被放入applicationListeners缓存集合
  10. */
  11. for (ApplicationListener<?> listener : getApplicationListeners()) {
  12. //注册到ApplicationEventMulticaster中
  13. getApplicationEventMulticaster().addApplicationListener(listener);
  14. }
  15. /*
  16. * 随后将beanFactory中的所有ApplicationListener类型的bean定义对应的beanName找出来
  17. * 包括非单例的bean定义、FactoryBean本身以及Factory创建的Bean
  18. * 不会初始化对应的bean实例,也不会初始化FactoryBean本身以及Factory创建的Bean
  19. */
  20. //从beanFactory中获取所有ApplicationListener类型的beanName数组
  21. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  22. //遍历listenerBeanNames数组
  23. for (String listenerBeanName : listenerBeanNames) {
  24. //将listenerBeanName注册到ApplicationEventMulticaster中
  25. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  26. }
  27. /*
  28. * 通过应用程序广播器对注册的监听器发布所有收集的早期应用程序事件
  29. * earlyApplicationEvents默认就是空集合
  30. */
  31. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  32. //earlyApplicationEvents置为null
  33. this.earlyApplicationEvents = null;
  34. if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
  35. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  36. //调用multicastEvent方法按照遍历顺序发布早期应用程序事件
  37. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  38. }
  39. }
  40. }
  41. //--------AbstractApplicationContext的相关属性
  42. /**
  43. * 调用addApplicationListener方法添加的listener监听器集合
  44. */
  45. private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  46. /**
  47. * AbstractApplicationContext的方法
  48. * <p>
  49. * 返回监听器集合
  50. */
  51. public Collection<ApplicationListener<?>> getApplicationListeners() {
  52. return this.applicationListeners;
  53. }
  54. /**
  55. * 在广播器和监听器被设置之前发布的应用程序事件,被收集到该集合中
  56. */
  57. @Nullable
  58. private Set<ApplicationEvent> earlyApplicationEvents;

  手动注册的监听器实例和Spring管理的监听器beanName将分别被注册到applicationListeners和applicationListenerBeans缓存中:

  1. /*AbstractApplicationEventMulticaster的方法*/
  2. /**
  3. * 默认检索器
  4. */
  5. private final ListenerRetriever defaultRetriever = new ListenerRetriever(false);
  6. /**
  7. * 检索器缓存,以提高效率
  8. */
  9. final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<>(64);
  10. /**
  11. * 互斥量
  12. */
  13. private Object retrievalMutex = this.defaultRetriever;
  14. /**
  15. * AbstractApplicationEventMulticaster的方法
  16. * <p>
  17. * 添加自定义监听器实例
  18. */
  19. @Override
  20. public void addApplicationListener(ApplicationListener<?> listener) {
  21. //加锁
  22. synchronized (this.retrievalMutex) {
  23. // 删除代理的目标对象监听器而是注册采用代理对象,以避免对同一监听器进行双重调用。
  24. Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
  25. if (singletonTarget instanceof ApplicationListener) {
  26. //删除代理目标对象
  27. this.defaultRetriever.applicationListeners.remove(singletonTarget);
  28. }
  29. //加入到默认检索器的applicationListeners集合
  30. this.defaultRetriever.applicationListeners.add(listener);
  31. //清除缓存
  32. this.retrieverCache.clear();
  33. }
  34. }
  35. /**
  36. * AbstractApplicationEventMulticaster的方法
  37. * <p>
  38. * 添加自定义监听器beanName
  39. */
  40. @Override
  41. public void addApplicationListenerBean(String listenerBeanName) {
  42. //加锁
  43. synchronized (this.retrievalMutex) {
  44. //加入到默认检索器的applicationListenerBeans集合
  45. this.defaultRetriever.applicationListenerBeans.add(listenerBeanName);
  46. //清除缓存
  47. this.retrieverCache.clear();
  48. }
  49. }
  50. /**
  51. * AbstractApplicationEventMulticaster的内部类
  52. * <p>
  53. * 封装一组特定目标监听器的检索器。
  54. */
  55. private class ListenerRetriever {
  56. public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  57. public final Set<String> applicationListenerBeans = new LinkedHashSet<>();
  58. private final boolean preFiltered;
  59. public ListenerRetriever(boolean preFiltered) {
  60. this.preFiltered = preFiltered;
  61. }
  62. }

3 ApplicationListenerDetector注册事件监听器

  Spring 4.3.4版本出现的ApplicationListenerDetector是一个BeanPostProcessor,因此在每一个Spring管理的普通bean初始化之后都会执行其postProcessAfterInitialization方法,如果某个初始化的Bean是一个singleton的ApplicationListener,那么就会有可能被添加到AbstractApplicationEventMulticaster内部的defaultRetriever的applicationListeners集合缓存中。
在这里插入图片描述
  我们没有手动注册ApplicationListenerDetector,那么这个后处理器一定是Spring为我们添加的了,那么它是在什么时候被添加的呢?实际上,它是在IoC容器初始化的早期的prepareBeanFactory方法中被自动添加的,此时后处理器还没有被初始化,Bean更没有被创建!
在这里插入图片描述
  看看它的原理,很简单,如果是单例的ApplicationListener,那么存入applicationEventMulticaster的defaultRetriever的applicationListeners缓存中。注意,这里添加的是监听器实例到applicationListeners缓存中,而在上一步registerListeners则是添加的监听器的beanName到applicationListenerBeans缓存中。因此beanName指向的监听器实例可能已经被添加了!

  1. /**
  2. * ApplicationListenerDetector的属性
  3. */
  4. private final transient Map<String, Boolean> singletonNames = new ConcurrentHashMap<>(256);
  5. /**
  6. * ApplicationListenerDetector的方法
  7. * <p>
  8. * bean实例化完毕之后,方法或者字段依赖注入之前调用
  9. * 它会缓存该Bean是否是单例Bean,用于后面添加监听器的时候可以直接判断
  10. */
  11. @Override
  12. public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
  13. //如果当前bean类型属于ApplicationListener,那么存入缓存
  14. //key为beanName,value为当前bean是否是单例的,如果是单例则为true,否则为false
  15. if (ApplicationListener.class.isAssignableFrom(beanType)) {
  16. this.singletonNames.put(beanName, beanDefinition.isSingleton());
  17. }
  18. }
  19. /**
  20. 1. ApplicationListenerDetector的方法
  21. 2. <p>
  22. 3. bean初始化完毕之后调用
  23. */
  24. @Override
  25. public Object postProcessAfterInitialization(Object bean, String beanName) {
  26. //如果属于ApplicationListener
  27. if (bean instanceof ApplicationListener) {
  28. Boolean flag = this.singletonNames.get(beanName);
  29. //如果是单例的,那么存入applicationEventMulticaster的defaultRetriever的applicationListeners缓存中
  30. if (Boolean.TRUE.equals(flag)) {
  31. // singleton bean (top-level or inner): register on the fly
  32. this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
  33. }
  34. //否则,输出警告
  35. else if (Boolean.FALSE.equals(flag)) {
  36. if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
  37. // inner bean with other scope - can't reliably process events
  38. logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
  39. "but is not reachable for event multicasting by its containing ApplicationContext " +
  40. "because it does not have singleton scope. Only top-level listener beans are allowed " +
  41. "to be of non-singleton scope.");
  42. }
  43. //移除缓存
  44. this.singletonNames.remove(beanName);
  45. }
  46. }
  47. return bean;
  48. }

4 EventListenerMethodProcessor解析@EventListener注解

  在学习Spring事件发布机制的时候,我们就说过Spring4.2开始支持@EventListener注解绑定的方法来监听事件,这是一种非常方便快捷的方式!该注解是通过一个EventListenerMethodProcessor类型的后处理器解析的,注解标注的方法将被解析为一个ApplicationListenerMethodAdapter监听器对象,这是适配器模式的应用。
在这里插入图片描述
  我们没有手动注册EventListenerMethodProcessor,那么这个后处理器一定是Spring为我们添加的了,那么它是在什么时候被添加的呢?实际上,它是在解析<context:annotation-config/>标签或者<context:component-scan/>标签或者初始化AnnotationConfigApplicationContext容器时在registerAnnotationConfigProcessors方法中添加的,此时后处理器还没有被初始化,普通Bean更没有被创建!
在这里插入图片描述
  与ApplicationListenerDetector的不同的是,EventListenerMethodProcessor的主要实现逻辑是通过SmartInitializingSingleton接口的afterSingletonsInstantiated回调方法来完成@EventListener注解解析的。
  EventListenerMethodProcessor的源码也很简单,我们看看它的实现逻辑!

  1. 首先在postProcessBeanFactory方法中会查找EventListenerFactory类型的bean,EventListenerFactory真正用于包装@EventListener方法为一个ApplicationListener。

    1. 默认情况下,Spring会默认注册一个DefaultEventListenerFactory,他同样是在registerAnnotationConfigProcessors方法中注册EventListenerMethodProcessor之后立即注册的。它会将方法包装为一个ApplicationListenerMethodAdapter类型的ApplicationListener,这是适配器模式的应用。
  2. 然后在afterSingletonsInstantiated方法中遍历所有的bean,查找使用了@EventListener注解的方法,并且会将这些方法应用与此前找到的EventListenerFactory,在解析成功之后,会将ApplicationListener,同样注册到applicationEventMulticaster内部的defaultRetriever的applicationListeners集合中。

   根据上面的规则我们知道,如果是采用实现ApplicationListener自定义的监听器,那么将会监听到所有时段发布的事件,而如果是采用@EventListener方法定义的监听器,由于它的解析时间非常的晚,是在所有的bean实例化、初始化完毕之后才会解析,那么在此前发布的事件将无法被监听到,比如早期事件集合earlyApplicationEvents中发布的事件,比如@PostConstruct方法中发布的事件,这种丢失事件的行为是我们一定要注意的!

  1. public class EventListenerMethodProcessor
  2. implements SmartInitializingSingleton, ApplicationContextAware, BeanFactoryPostProcessor {
  3. protected final Log logger = LogFactory.getLog(getClass());
  4. @Nullable
  5. private ConfigurableApplicationContext applicationContext;
  6. @Nullable
  7. private ConfigurableListableBeanFactory beanFactory;
  8. /**
  9. * 真正用于包装@EventListener方法为一个ApplicationListener的EventListenerFactory
  10. */
  11. @Nullable
  12. private List<EventListenerFactory> eventListenerFactories;
  13. /**
  14. * 用于解析SPEL表达式的评估器
  15. */
  16. private final EventExpressionEvaluator evaluator = new EventExpressionEvaluator();
  17. /**
  18. * 类型检查的缓存
  19. */
  20. private final Set<Class<?>> nonAnnotatedClasses = Collections.newSetFromMap(new ConcurrentHashMap<>(64));
  21. /**
  22. * 该回调方法在EventListenerMethodProcessor本身被实例化之后回调,用于设置applicationContext
  23. */
  24. @Override
  25. public void setApplicationContext(ApplicationContext applicationContext) {
  26. Assert.isTrue(applicationContext instanceof ConfigurableApplicationContext,
  27. "ApplicationContext does not implement ConfigurableApplicationContext");
  28. this.applicationContext = (ConfigurableApplicationContext) applicationContext;
  29. }
  30. /**
  31. * 该回调方法是在注册BeanPostProcessor以及实例化普通Bean之前完成的
  32. * <p>
  33. * 该方法用于查找并初始化所有的EventListenerFactory类型的bean
  34. * EventListenerFactory可用于解析对应的@EventListener注解方法,并返回一个ApplicationListener
  35. */
  36. @Override
  37. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  38. this.beanFactory = beanFactory;
  39. //查找并初始化所有EventListenerFactory类型的bean,key为beanName,value为bean实例
  40. Map<String, EventListenerFactory> beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
  41. //获取所有的EventListenerFactory
  42. List<EventListenerFactory> factories = new ArrayList<>(beans.values());
  43. //通过AnnotationAwareOrderComparator对其进行排序,因此支持Ordered、PriorityOrdered接口,以及@Order、@Priority注解的排序
  44. AnnotationAwareOrderComparator.sort(factories);
  45. //保存起来
  46. this.eventListenerFactories = factories;
  47. }
  48. /**
  49. * 该回调方法在所有非延迟初始化的单例bean初始化完毕之后才会进行回调,属于一个非常晚期的回调了
  50. */
  51. @Override
  52. public void afterSingletonsInstantiated() {
  53. ConfigurableListableBeanFactory beanFactory = this.beanFactory;
  54. Assert.state(this.beanFactory != null, "No ConfigurableListableBeanFactory set");
  55. //匹配的类型是Object,因此会获取Spring管理的所有的beanName。看起来不是很优雅的样子……
  56. String[] beanNames = beanFactory.getBeanNamesForType(Object.class);
  57. //遍历
  58. for (String beanName : beanNames) {
  59. //确定是否是作用域代理
  60. if (!ScopedProxyUtils.isScopedTarget(beanName)) {
  61. Class<?> type = null;
  62. try {
  63. //获取bean的原始的类型(可能被代理了)
  64. type = AutoProxyUtils.determineTargetClass(beanFactory, beanName);
  65. } catch (Throwable ex) {
  66. // An unresolvable bean type, probably from a lazy bean - let's ignore it.
  67. if (logger.isDebugEnabled()) {
  68. logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
  69. }
  70. }
  71. if (type != null) {
  72. //作用域对象的兼容处理
  73. if (ScopedObject.class.isAssignableFrom(type)) {
  74. try {
  75. Class<?> targetClass = AutoProxyUtils.determineTargetClass(
  76. beanFactory, ScopedProxyUtils.getTargetBeanName(beanName));
  77. if (targetClass != null) {
  78. type = targetClass;
  79. }
  80. } catch (Throwable ex) {
  81. // An invalid scoped proxy arrangement - let's ignore it.
  82. if (logger.isDebugEnabled()) {
  83. logger.debug("Could not resolve target bean for scoped proxy '" + beanName + "'", ex);
  84. }
  85. }
  86. }
  87. try {
  88. /*
  89. * 最关键的方法,真正的处理bean中的@EventListener方法
  90. */
  91. processBean(beanName, type);
  92. } catch (Throwable ex) {
  93. throw new BeanInitializationException("Failed to process @EventListener " +
  94. "annotation on bean with name '" + beanName + "'", ex);
  95. }
  96. }
  97. }
  98. }
  99. }
  100. /**
  101. * 处理bean中的@EventListener方法,一个方法封装为一个ApplicationListenerMethodAdapter对象
  102. */
  103. private void processBean(final String beanName, final Class<?> targetType) {
  104. //如果nonAnnotatedClasses缓存中不包含当前类型,并且给定类是承载指定EventListener注解的候选项
  105. //并且不是spring容器的内部bean,如果类路径以"org.springframework."开头,并且没有被@Component标注,那么就是spring容器内部的类
  106. //以上条件满足,当前class可以被用来查找@EventListener注解方法
  107. if (!this.nonAnnotatedClasses.contains(targetType) &&
  108. AnnotationUtils.isCandidateClass(targetType, EventListener.class) &&
  109. !isSpringContainerClass(targetType)) {
  110. Map<Method, EventListener> annotatedMethods = null;
  111. try {
  112. //查找当前class内部的具有@EventListener注解的方法
  113. annotatedMethods = MethodIntrospector.selectMethods(targetType,
  114. (MethodIntrospector.MetadataLookup<EventListener>) method ->
  115. AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class));
  116. } catch (Throwable ex) {
  117. // An unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
  118. if (logger.isDebugEnabled()) {
  119. logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex);
  120. }
  121. }
  122. //如果此类没有@EventListener注解的方法,那么记入nonAnnotatedClasses缓存,下一次预检此类型则直接跳过
  123. if (CollectionUtils.isEmpty(annotatedMethods)) {
  124. this.nonAnnotatedClasses.add(targetType);
  125. if (logger.isTraceEnabled()) {
  126. logger.trace("No @EventListener annotations found on bean class: " + targetType.getName());
  127. }
  128. //如果此类拥有@EventListener注解的方法
  129. } else {
  130. // Non-empty set of methods
  131. ConfigurableApplicationContext context = this.applicationContext;
  132. Assert.state(context != null, "No ApplicationContext set");
  133. //获取此前所有的EventListenerFactory
  134. List<EventListenerFactory> factories = this.eventListenerFactories;
  135. Assert.state(factories != null, "EventListenerFactory List not initialized");
  136. //遍历所有具有该注解的方法
  137. for (Method method : annotatedMethods.keySet()) {
  138. //遍历EventListenerFactory
  139. for (EventListenerFactory factory : factories) {
  140. //如果此factory支持解析当前方法
  141. if (factory.supportsMethod(method)) {
  142. //根据对象的类型(可能是代理对象类型),解析当前方法成为一个可执行方法
  143. //如果方法是私有的,并且方法不是静态的,并且当前类型是一个Spring通用的代理类型,那么将会抛出异常
  144. //普通Spring AOP、事务、@Async等创建的代理都是SpringProxy类型,而@Configuration代理就不是SpringProxy类型
  145. //如果当前类型是JDK代理,并且方法不是从从代理的接口中实现的,那么同样会抛出异常
  146. Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
  147. //调用factory#createApplicationListener方法根据给定的method创建一个ApplicationListener
  148. //默认情况下这里的ApplicationListener实际上是一个ApplicationListenerMethodAdapter,这是适配器模式
  149. ApplicationListener<?> applicationListener =
  150. factory.createApplicationListener(beanName, targetType, methodToUse);
  151. //如果属于ApplicationListenerMethodAdapter,那么还要进行初始化
  152. //主要是设置一个EventExpressionEvaluator,用于解析@EventListener中的condition属性的 SpEL 表达式
  153. if (applicationListener instanceof ApplicationListenerMethodAdapter) {
  154. ((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
  155. }
  156. //将方法转换成的ApplicationListenerMethodAdapter同样添加到applicationEventMulticaster内部的
  157. //defaultRetriever的applicationListeners集合中
  158. context.addApplicationListener(applicationListener);
  159. //如果有一个factory能够解析成功,那么不在应用后续的factory,结束循环,解析结束
  160. break;
  161. }
  162. }
  163. }
  164. if (logger.isDebugEnabled()) {
  165. logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" +
  166. beanName + "': " + annotatedMethods);
  167. }
  168. }
  169. }
  170. }
  171. private static boolean isSpringContainerClass(Class<?> clazz) {
  172. return (clazz.getName().startsWith("org.springframework.") &&
  173. !AnnotatedElementUtils.isAnnotated(ClassUtils.getUserClass(clazz), Component.class));
  174. }
  175. }

4.1 selectInvocableMethod查找可调用方法

  AopUtils.selectInvocableMethod用于根据对象的类型(可能是代理对象类型),解析当前方法成为一个真正可执行方法,为什么要这么做?因为实际执行该方法的对象可能是一个代理对象,虽然@EventListener方法所属的类本身并不会被代理(因此它只是将方法转换为一个listener,而比如@Async方法所属的类本身就会被代理),但是仍然可能由于被其他特性代理而的成为一个代理对象,进而可能抛出各种异常:

  1. 如果要执行的方法是私有的,并且方法不是静态的,并且当前类型是一个Spring通用的SpringProxy代理类型,那么将会抛出IllegalStateException异常:“Need to invoke method ‘%s’ found on proxy for target class ‘%s’ but cannot……”。

    1. 普通Spring AOP、事务、@Async等创建的代理都是SpringProxy类型,而@Configuration代理就不是SpringProxy类型。
  2. 如果当前类型是JDK代理,并且方法不是从代理类实现的接口中实现的,那么该方法无法被代理对象调用到,因此同样会抛出异常IllegalStateException异常:“Need to invoke method ‘%s’ declared on target class ‘%s’,……”。

    1. 比如@EventListener方法位于接口的实现类中,但是这个方法是该实现类自己的,那么在启动时就会抛出该异常!

    /**

    • AopUtils的方法
    • 在目标类型上选择可调用的方法:如果给定方法在目标类型上公开,则给定方法本身,或在目标类型的接口之一或目标类型本身上选择相应的方法。
      *
    • @param method 要检查的方法
    • @param targetType 要搜索方法的目标类型(可能是 AOP 代理对象类型)
    • @return 目标类型上的相应可调用方法
    • @throws IllegalStateException 如果给定方法在给定目标类型上不可调用(通常是由于代理不匹配)
      */
      public static Method selectInvocableMethod(Method method, @Nullable Class<?> targetType) {

      if (targetType == null) {

      1. return method;

      }
      //在目标类型上选择可调用的方法:如果实际方法在目标类型上公开,则给定方法本身,或在目标类型的接口之一或目标类型本身上选择相应的方法。
      Method methodToUse = MethodIntrospector.selectInvocableMethod(method, targetType);
      //如果方法是私有的,并且方法不是静态的,并且当前类型是一个Spring通用的代理类型,那么将会抛出异常
      //普通Spring AOP、事务、@Async等创建的代理都是SpringProxy类型,而@Configuration代理就不是SpringProxy类型
      if (Modifier.isPrivate(methodToUse.getModifiers()) && !Modifier.isStatic(methodToUse.getModifiers()) &&

      1. SpringProxy.class.isAssignableFrom(targetType)) {
      2. throw new IllegalStateException(String.format(
      3. "Need to invoke method '%s' found on proxy for target class '%s' but cannot " +
      4. "be delegated to target bean. Switch its visibility to package or protected.",
      5. method.getName(), method.getDeclaringClass().getSimpleName()));

      }
      return methodToUse;
      }

  1. /**
  2. * MethodIntrospector的方法
  3. * <p>
  4. * 在目标类型上选择可调用的方法:如果实际方法在目标类型上公开,则给定方法本身,或在目标类型的接口之一或目标类型本身上选择相应的方法。
  5. *
  6. * @param method 检查的方法
  7. * @param targetType 要搜索的方法的目标类型(可能代理对象类型)
  8. * @return a corresponding invocable method on the target type
  9. * @throws IllegalStateException 如果给定方法在给定目标类型上不可调用(通常是由于代理不匹配)
  10. */
  11. public static Method selectInvocableMethod(Method method, Class<?> targetType) {
  12. //如果目标类型属于方法所属的类型,那么直接返回方法就可以了,这对CGLIB代理来说是成立的,但是JDK代理就不行了
  13. if (method.getDeclaringClass().isAssignableFrom(targetType)) {
  14. return method;
  15. }
  16. try {
  17. //获取方法名
  18. String methodName = method.getName();
  19. //获取参数类型
  20. Class<?>[] parameterTypes = method.getParameterTypes();
  21. //如果遍历目标类型实现的接口
  22. for (Class<?> ifc : targetType.getInterfaces()) {
  23. try {
  24. //返回接口中的同名同参数类型的方法
  25. //如果是JDK的代理,但是@EventListener方法不是从接口中实现的方法,那么由于找不到方法将抛出异常NoSuchMethodException
  26. return ifc.getMethod(methodName, parameterTypes);
  27. } catch (NoSuchMethodException ex) {
  28. // Alright, not on this interface then...
  29. }
  30. }
  31. // 最后从代理类本身尝试获取方法的绝望尝试...,一般都是失败的
  32. return targetType.getMethod(methodName, parameterTypes);
  33. } catch (NoSuchMethodException ex) {
  34. //如果找不到方法,将会抛出IllegalStateException异常
  35. throw new IllegalStateException(String.format(
  36. "Need to invoke method '%s' declared on target class '%s', " +
  37. "but not found in any interface(s) of the exposed proxy type. " +
  38. "Either pull the method up to an interface or switch to CGLIB " +
  39. "proxies by enforcing proxy-target-class mode in your configuration.",
  40. method.getName(), method.getDeclaringClass().getSimpleName()));
  41. }
  42. }

5 publishEvent发布事件

  经过上面的几个步骤(都在在IoC容器启动时完成的),已经完成了事件发布的基本准备工作,包括ApplicationEventMulticaster的初始化、自定义的ApplicationListener的初始化、@EventListener方法的解析……这些操作都是在IoC容器启动、初始化过程中完成的。现在,可以正式发布事件了(也就是调用我们的发布事件的代码)!
  Spring 4.2开始,AbstractApplicationContext提供了两个可调用的发布事件的接口,并且其中一个接口支持发布任意类型(Object类型 )的事件。

  1. /**
  2. * 将给定事件发布到所有监听器。
  3. *
  4. * @param event 要发布的事件,ApplicationEvent类型
  5. */
  6. @Override
  7. public void publishEvent(ApplicationEvent event) {
  8. //调用另一个方法
  9. publishEvent(event, null);
  10. }
  11. /**
  12. 1. 将给定事件发布到所有监听器。
  13. 2. 3. @param event 要发布的事件,ApplicationEvent类型
  14. */
  15. @Override
  16. public void publishEvent(Object event) {
  17. //调用另一个方法
  18. publishEvent(event, null);
  19. }

  它们都调用另一个内部同名publishEvent方法!该方法主要步骤为:

  1. 如果发布的事件不属于ApplicationEvent,那么转换为PayloadApplicationEvent类型的通用事件;否则强转为ApplicationEvent。
  2. 如果earlyApplicationEvents不为null,这说明此时registerListeners方法还没执行完毕(上面讲过registerListeners方法会将earlyApplicationEvents置为null),监听器可能还没有注册,此时发布的事件属于应用早期事件,那么存入早期应用事件集合中。
  3. 如果earlyApplicationEvents为null,表示registerListeners方法已执行完毕,广播器初始化完毕,监听器注册完毕,此时可以直接通过广播器的multicastEvent方法进行事件广播。
  4. 如果存在父容器,那么也通过父上下文容器的publishEvent方法发布事件。

    /**

    • AbstractApplicationContext的属性
    • 在应用事件广播器初始化之前发布的事件集合,即早期事件集合
      */
      @Nullable
      private Set earlyApplicationEvents;

    /**

    • AbstractApplicationContext的方法
    • 将给定事件发布到所有监听器。
      *
    • @param event 要发布的事件(可能是一个ApplicationEvent对象或一个要转换为PayloadApplicationEvent的Object)
    • @param eventType 已解析的事件类型(如果已知)
      */
      protected void publishEvent(Object event, @Nullable ResolvableType eventType) {

      Assert.notNull(event, “Event must not be null”);
      ApplicationEvent applicationEvent;
      //如果本来就属于ApplicationEvent,那么强制转型
      if (event instanceof ApplicationEvent) {

      1. applicationEvent = (ApplicationEvent) event;

      }
      //如果是其它类型,那么包装为一个PayloadApplicationEvent类型
      //PayloadApplicationEvent是ApplicationEvent的一个子类,用于承载通用事件
      else {

      1. applicationEvent = new PayloadApplicationEvent<>(this, event);
      2. //如果eventType为null,那么获取可解析的类型
      3. //它会将PayloadApplicationEvent的泛型设置为承载的event的类型
      4. if (eventType == null) {
      5. eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
      6. }

      }
      /*

      • 如果earlyApplicationEvents不为null,说明此时registerListeners方法还没执行完毕,监听器可能还没有注册
      • 此时发布的事件属于应用早期事件,那么这个事件将会存入早期应用事件集合中
        */
        if (this.earlyApplicationEvents != null) {

        this.earlyApplicationEvents.add(applicationEvent);
        } else {

        /*

        • 否则,表示registerListeners方法已执行完毕,监听器注册完毕
        • 此时可以直接通过广播器的multicastEvent方法进行事件广播
          */
          getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
          }
          // 如果存在父容器,那么也通过父上下文容器发布事件
          if (this.parent != null) {

          if (this.parent instanceof AbstractApplicationContext) {

          ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
          } else {

          this.parent.publishEvent(event);
          }
          }
          }

5.1 multicastEvent广播事件

  从上面的源码中可知,最终是通过委托广播器的multicastEvent方法进行事件广播的,因此该方法是重点方法! Spring提供了为一个内置的广播器的实现就是SimpleApplicationEventMulticaster,它的uml类图如下:
在这里插入图片描述
  首先会获取可以匹配当前事件类型的监听器,然后会获取执行器。如果执行器不为null,那么通过执行器异步的执行监听器的调用,默认就是null,因此,默认是直接在调用线程中执行监听器的调用,这样的话,实际上发布事件和接收事件并处理的线程就是同一个线程,许多开发者预期发布事件与接收事件并处理的操作是真正异步、解耦的,如果有这样的需求,则一定要注意这一点。当然如果不在这里设置执行器,在监听器方法上使用@Async注解也能实现异步事件处理,这是很常用的!

  1. /**
  2. 1. SimpleApplicationEventMulticaster的方法
  3. 2. <p>
  4. 3. 将给定的应用程序事件广播到到适当的监听器。
  5. 4. 5. @param event 广播事件
  6. 6. @param eventType 事件类型,可以为null
  7. */
  8. @Override
  9. public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
  10. //获取解析的类型,如果eventType为null那么将当前事件的class作为类型(通常用于本来就是ApplicationEvent类型的事件)
  11. ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
  12. //获取任务执行器,SimpleApplicationEventMulticaster可以指定一个事件任务执行器和一个异常处理器,用于实现异步事件
  13. Executor executor = getTaskExecutor();
  14. /*
  15. * 根据事件和事件类型获取可以支持该事件的监听器并依次进行调用,这里获取的监听器并不一定都会执行
  16. */
  17. for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  18. if (executor != null) {
  19. /*
  20. * 如果执行器不为null,那么通过执行器异步的执行监听器的调用,默认就是null
  21. */
  22. executor.execute(() -> invokeListener(listener, event));
  23. } else {
  24. /*
  25. * 否则,直接在调用线程中执行监听器的调用,这样的话,实际上发布事件和接收事件并处理的线程就是同一个线程
  26. * 许多开发者预期发布事件与接收事件并处理的操作是真正异步、解耦的,如果有这样的需求,则一定要注意这一点
  27. * 当前如果不在这里设置执行器,在监听器方法上使用@Async注解也能实现异步事件处理,这是很常用的!
  28. */
  29. invokeListener(listener, event);
  30. }
  31. }
  32. }

5.1.1 getApplicationListeners获取监听器

  该方法返回与给定事件类型匹配的应用程序监听器集合,并还会将监听器存入缓存中,后续遇到该类型的事件时,将会直接从缓存中获取!
  该方法会遍历所有监听器并通过supportsEvent方法来判断是否支持该事件类型:

  1. 如果是普通ApplicationListener监听器的实现,会被包装为一个GenericApplicationListenerAdapter,并且会判断监听器的泛型事件类型是否与给定事件的类型匹配或者兼容。
  2. 如果是@EventListener监听器,对应着ApplicationListenerMethodAdapter,它则是判断方法参数以及注解中的value、classes属性指定的类型是否与给定事件的类型匹配或者兼容,或者,如果该事件为PayloadApplicationEvent类型,则判断与该事件的有效载荷的类型是否匹配或者兼容。

    1. 也就是说@EventListener方法参数以及注解value、classes属性的类型可以直接是事件的载荷类型。也就是只要与发布的事件类型一致,就能监听到,不一定非得是一个真正的ApplicationEvent事件类型。
  3. 根据上面的判断依据,细心的我们会发现,对于@EventListener方法事件监听器,还有一个condition属性并没有校验和判断,但是该属性同样可以用于指定匹配条件,只有条件满足时,此监听器才会真正的执行。因此,实际上该方法获取监听器集合并不一定是最终会执行的监听器集合!那么condition条件在哪里判断呢?在后面的方法中,我们下面会讲到!

  还有以下几个注意点:

  1. 该方法设置了缓存,这样在后续触发该类型的事件时将直接从缓存获取。
  2. 该方法对于延迟初始化(比如@Lazy)或者非singleton作用域的ApplicationListener进行了初始化。
  3. 对于非singleton作用域的监听器则仅仅缓存的beanName而非创建的监听器实例,这样在后续从缓存获取监听器时会从新创建,从而保证作用域的语义

    /**

    • AbstractApplicationEventMulticaster的方法
    • 返回与给定事件类型匹配的应用程序监听器集合,不匹配的监听器会提前被排除。
      *
    • @param event 要传播的事件。允许根据缓存的匹配信息尽早排除不匹配的侦听器。
    • @param eventType 事件类型
    • @return 监听器列表
      */
      protected Collection> getApplicationListeners(

      1. ApplicationEvent event, ResolvableType eventType) {

      //获取需要传递的源数据
      Object source = event.getSource();
      //获取源类型
      Class<?> sourceType = (source != null ? source.getClass() : null);
      //根据事件类型和源类型创建一个缓存key对象
      ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);

      //快速检查ConcurrentHashMap上的现有的缓存…
      ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
      //如果检索器不为null,那么返回检索器中缓存的监听器,这也是为什么在此前添加监听器之后,这个缓存会被清空的原因
      if (retriever != null) {

      1. return retriever.getApplicationListeners();

      }
      //如果没有缓存
      if (this.beanClassLoader == null ||

      1. (ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) &&
      2. (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) {
      3. // 加锁,完全同步的生成监听器的缓存
      4. synchronized (this.retrievalMutex) {
      5. //加锁之后再次尝试从缓存中获取
      6. retriever = this.retrieverCache.get(cacheKey);
      7. //如果检索器不为null,那么返回检索器中缓存的监听器,这也是为什么在此前添加监听器之后,这个缓存会被清空的原因
      8. if (retriever != null) {
      9. return retriever.getApplicationListeners();
      10. }
      11. //新建一个检索器
      12. retriever = new ListenerRetriever(true);
      13. //实际检索给定事件和源类型对应的监听器,并将结果缓存到新建的ListenerRetriever中
      14. //检索规则就是
      15. Collection<ApplicationListener<?>> listeners =
      16. retrieveApplicationListeners(eventType, sourceType, retriever);
      17. //存入缓存中
      18. this.retrieverCache.put(cacheKey, retriever);
      19. //返回找到的监听器
      20. return listeners;
      21. }

      } else {

      1. // 直接检索给定事件和源类型对应的监听器,也不需要缓存
      2. return retrieveApplicationListeners(eventType, sourceType, null);

      }
      }

  1. /**
  2. * AbstractApplicationEventMulticaster的方法
  3. * <p>
  4. * 实际上检索给定事件和源类型的应用程序监听器。
  5. *
  6. * @param eventType 事件类型
  7. * @param sourceType 事件源类型
  8. * @param retriever 监听器检索器,用于缓存找到的监听器,可以为null
  9. * @return 适用于给定事件和源类型的应用程序监听器列表
  10. */
  11. private Collection<ApplicationListener<?>> retrieveApplicationListeners(
  12. ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable ListenerRetriever retriever) {
  13. //所有的监听器
  14. List<ApplicationListener<?>> allListeners = new ArrayList<>();
  15. //手动注册的监听器
  16. Set<ApplicationListener<?>> listeners;
  17. //Spring管理的监听器Bean
  18. Set<String> listenerBeans;
  19. //初始化,集合,直接从defaultRetriever获取缓存的监听器
  20. synchronized (this.retrievalMutex) {
  21. //这里面可能包括不匹配的监听器
  22. listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners);
  23. listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans);
  24. }
  25. //添加以编程方式注册的监听器
  26. for (ApplicationListener<?> listener : listeners) {
  27. /*
  28. * 是否支持该事件类型和事件源类型
  29. *
  30. * 如果是普通ApplicationListener监听器:
  31. * 则判断监听器的泛型事件类型是否与给定事件的类型匹配或者兼容
  32. * 如果是@EventListener监听器:
  33. * 则是判断方法参数以及注解中的value、classes属性指定的类型是否与给定事件的类型匹配或者兼容
  34. * 或者,如果该事件为PayloadApplicationEvent类型,则判断与该事件的有效载荷的类型是否匹配或者兼容
  35. *
  36. * 也就是说@EventListener方法参数以及注解value、classes属性的类型可以直接是事件的载荷类型
  37. * 也就是只要与发布的事件类型一致,就能监听到,不一定非得是一个真正的ApplicationEvent事件类型
  38. */
  39. if (supportsEvent(listener, eventType, sourceType)) {
  40. //如果检索器不为null,那么存入该检索器,用于缓存
  41. if (retriever != null) {
  42. retriever.applicationListeners.add(listener);
  43. }
  44. //把支持该事件的监听器加入到allListeners集合
  45. allListeners.add(listener);
  46. }
  47. }
  48. // 尝试添加通过Spring注册的监听器,虽然在此前的ApplicationListenerDetector中已经注册了一部分
  49. // 但是仍然可能存在@Lazy的监听器或者prototype的监听器,那么在这里初始化
  50. if (!listenerBeans.isEmpty()) {
  51. ConfigurableBeanFactory beanFactory = getBeanFactory();
  52. //遍历beanName
  53. for (String listenerBeanName : listenerBeans) {
  54. try {
  55. /*是否支持该事件类型*/
  56. if (supportsEvent(beanFactory, listenerBeanName, eventType)) {
  57. //如果支持,那么这里通过Spring初始化当前监听器实例
  58. ApplicationListener<?> listener =
  59. beanFactory.getBean(listenerBeanName, ApplicationListener.class);
  60. //如果已获取的集合中不包含该监听器,并且当前监听器实例支持支持该事件类型和事件源类型
  61. if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
  62. //如果检索器不为null,那么存入该检索器,用于缓存
  63. if (retriever != null) {
  64. //如果是singleton的监听器,那么有可能会是@Lazy导致懒加载的,那么直接将实例加入到applicationListeners集合
  65. if (beanFactory.isSingleton(listenerBeanName)) {
  66. retriever.applicationListeners.add(listener);
  67. } else {
  68. //如果是其他作用域的监听器,比如prototype,这表示在每次触发时需要创建新的监听器实例
  69. //那么不能缓存该监听器实例,而是将监听器的beanName加入到applicationListenerBeans集合
  70. retriever.applicationListenerBeans.add(listenerBeanName);
  71. }
  72. }
  73. //把支持该事件的监听器加入到allListeners集合
  74. allListeners.add(listener);
  75. }
  76. } else {
  77. // 将不匹配该事件的singleton的监听器实例移除
  78. Object listener = beanFactory.getSingleton(listenerBeanName);
  79. if (retriever != null) {
  80. retriever.applicationListeners.remove(listener);
  81. }
  82. //同样从要返回的集合中移除
  83. allListeners.remove(listener);
  84. }
  85. } catch (NoSuchBeanDefinitionException ex) {
  86. // Singleton listener instance (without backing bean definition) disappeared -
  87. // probably in the middle of the destruction phase
  88. }
  89. }
  90. }
  91. //最后使用AnnotationAwareOrderComparator比较器对监听器进行排序,这说明监听器支持order排序
  92. //该比较器支持Ordered、PriorityOrdered接口,以及@Order、@Priority注解的排序,比较优先级为PriorityOrdered>Ordered>@Ordered>@Priority,
  93. //排序规则是order值越小排序越靠前,优先级越高,没有order值则默认排在尾部,优先级最低。
  94. AnnotationAwareOrderComparator.sort(allListeners);
  95. //如果最终没有适用于给定事件的SpringBean
  96. if (retriever != null && retriever.applicationListenerBeans.isEmpty()) {
  97. //那么存入applicationListeners属性集合
  98. retriever.applicationListeners.clear();
  99. retriever.applicationListeners.addAll(allListeners);
  100. }
  101. //返回
  102. return allListeners;
  103. }

5.1.1.1 retriever.getApplicationListeners缓存获取监听器

  如果存在当前事件类型的缓存,那么通过retriever.getApplicationListeners()从缓存中获取监听器!唯一需要注意的一点就是对于非单例的监听器,每次调用都会通过beanName被初始化一次,这一点我们在上面就说过了!

  1. /**
  2. * AbstractApplicationEventMulticaster的内部类
  3. * <p>
  4. * 支持某个事件的监听器缓存器
  5. */
  6. private class ListenerRetriever {
  7. /**
  8. * 单例的监听器实例集合
  9. */
  10. public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  11. /**
  12. * 非单例的监听器beanName集合
  13. */
  14. public final Set<String> applicationListenerBeans = new LinkedHashSet<>();
  15. /**
  16. * 用于指示是否包括非单例的监听器
  17. * <p>
  18. * 创建缓存器时被指定为true
  19. */
  20. private final boolean preFiltered;
  21. public ListenerRetriever(boolean preFiltered) {
  22. this.preFiltered = preFiltered;
  23. }
  24. /**
  25. * 获取缓存中已存在的监听器实例,并且每次调用都会初始化非单例的监听器
  26. */
  27. public Collection<ApplicationListener<?>> getApplicationListeners() {
  28. List<ApplicationListener<?>> allListeners = new ArrayList<>(
  29. this.applicationListeners.size() + this.applicationListenerBeans.size());
  30. //首先把单例的监听器实例集合全部添加进去
  31. allListeners.addAll(this.applicationListeners);
  32. //如果存在非单例的监听器beanName
  33. if (!this.applicationListenerBeans.isEmpty()) {
  34. BeanFactory beanFactory = getBeanFactory();
  35. //那么遍历applicationListenerBeans集合
  36. for (String listenerBeanName : this.applicationListenerBeans) {
  37. try {
  38. //创建beanName对应的实例
  39. ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
  40. //如果可以使用非单例的监听器,并且此前不包含该监听器
  41. if (this.preFiltered || !allListeners.contains(listener)) {
  42. //那么加入到集合中返回
  43. allListeners.add(listener);
  44. }
  45. } catch (NoSuchBeanDefinitionException ex) {
  46. // Singleton listener instance (without backing bean definition) disappeared -
  47. // probably in the middle of the destruction phase
  48. }
  49. }
  50. }
  51. //如果不包括非单例的监听器或者applicationListenerBeans不为空,那么对监听器集合进行排序
  52. if (!this.preFiltered || !this.applicationListenerBeans.isEmpty()) {
  53. AnnotationAwareOrderComparator.sort(allListeners);
  54. }
  55. return allListeners;
  56. }
  57. }

5.1.2 invokeListener调用监听器

  在判断监听器可以处理当前类型的事件之后,会调用invokeListener方法来执行监听器,这里面就是处理事件的逻辑。
  可以看到,最终就是调用监听器的onApplicationEvent方法。

  1. /**
  2. * SimpleApplicationEventMulticaster的方法
  3. * <p>
  4. * 使用给定监听器传播给定事件。
  5. *
  6. * @param listener 要调用的listener
  7. * @param event 要传播的当前事件
  8. */
  9. protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
  10. //获取异常处理器,默认为null,同样可以自己设置
  11. ErrorHandler errorHandler = getErrorHandler();
  12. //如果异常处理器不为null,那么当抛出异常时使用异常处理器来处理
  13. if (errorHandler != null) {
  14. try {
  15. doInvokeListener(listener, event);
  16. } catch (Throwable err) {
  17. errorHandler.handleError(err);
  18. }
  19. } else {
  20. //如果异常处理器为null,那么直接调用方法,不处理可能抛出的异常
  21. doInvokeListener(listener, event);
  22. }
  23. }
  24. /**
  25. 1. SimpleApplicationEventMulticaster的方法
  26. 2. <p>
  27. 3. 真正的调用listener的方法
  28. 4. 5. @param listener 要调用的listener
  29. 6. @param event 要传播的当前事件
  30. */
  31. @SuppressWarnings({
  32. "rawtypes", "unchecked"})
  33. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  34. try {
  35. //调用listener的onApplicationEvent方法传播事件,这个方法就是处理事件的方法,不同的ApplicationListener有不同的实现
  36. //如果是ApplicationListenerMethodAdapter,即@EventListener方法监听器,那么首先会检验condition规则,只有符合规则才会真正的执行
  37. listener.onApplicationEvent(event);
  38. } catch (ClassCastException ex) {
  39. String msg = ex.getMessage();
  40. if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
  41. // Possibly a lambda-defined listener which we could not resolve the generic event type for
  42. // -> let's suppress the exception and just log a debug message.
  43. Log logger = LogFactory.getLog(getClass());
  44. if (logger.isTraceEnabled()) {
  45. logger.trace("Non-matching event type for listener: " + listener, ex);
  46. }
  47. } else {
  48. throw ex;
  49. }
  50. }
  51. }

5.1.2.1 onApplicationEvent

  最终会调用listener的onApplicationEvent方法传播事件,这个方法就是处理事件的方法,不同的ApplicationListener有不同的实现。
  如果是ApplicationListenerMethodAdapter,即@EventListener方法监听器,那么首先会检验condition规则,只有符合规则才会真正的执行,这里的规则可以是SPEL表达式,可以获取方法参数等信息来匹配。
  另外,@EventListener方法支持返回值,返回的结果将会被当作事件再次传播,直到返回null为止,这就是Spring的事件传递!

  通常情况下,返回结果的处理为:

  1. 如果返回数组或者Collection类型,那么将每一个元素作为一个事件依次发布;
  2. 如果返回其他普通类型,那么将该返回值整体作为一个事件发布;

    /**

    • ApplicationListenerMethodAdapter重写的方法
      */
      @Override
      public void onApplicationEvent(ApplicationEvent event) {

      processEvent(event);
      }

  1. /**
  2. * ApplicationListenerMethodAdapter的方法
  3. * <p>
  4. * 处理指定的应用程序事件,检查condition条件是否匹配并处理非空结果(如果有)。
  5. */
  6. public void processEvent(ApplicationEvent event) {
  7. //根据事件解析出调用方法需要传递的参数,如果为null,那么不会调用对应的@EventListener方法
  8. Object[] args = resolveArguments(event);
  9. //是否应该执行对应的@EventListener方法
  10. if (shouldHandle(event, args)) {
  11. //根据给定的参数执行对应的方法,获取方法的执行结果
  12. Object result = doInvoke(args);
  13. //如果返回值不为null,那么继续处理结果,会把结果作为事件继续发布
  14. //直到返回null,这也是@EventListener方法的特性
  15. if (result != null) {
  16. handleResult(result);
  17. } else {
  18. logger.trace("No result object given - no result to handle");
  19. }
  20. }
  21. }
  22. /**
  23. * ApplicationListenerMethodAdapter的方法
  24. * <p>
  25. * 是否应该执行@EventListener方法
  26. * 如果设置了@EventListener的condition条件属性,那么判断是否匹配条件,如果匹配那么返回true,否则返回false
  27. *
  28. * @param event 事件
  29. * @param args 方法参数
  30. * @return true表示应该执行,false表示不应该执行
  31. */
  32. private boolean shouldHandle(ApplicationEvent event, @Nullable Object[] args) {
  33. //如果方法参数为null,则返回false,即不执行
  34. if (args == null) {
  35. return false;
  36. }
  37. //获取@EventListener的condition条件属性
  38. String condition = getCondition();
  39. //如果设置了该属性的值
  40. if (StringUtils.hasText(condition)) {
  41. Assert.notNull(this.evaluator, "EventExpressionEvaluator must not be null");
  42. //那么判断是否匹配条件,如果匹配那么返回true,否则返回false
  43. return this.evaluator.condition(
  44. condition, event, this.targetMethod, this.methodKey, args, this.applicationContext);
  45. }
  46. //默认返回true
  47. return true;
  48. }
  49. /**
  50. * ApplicationListenerMethodAdapter的方法
  51. * <p>
  52. * 处理@EventListener方法的返回值
  53. */
  54. protected void handleResult(Object result) {
  55. //判断引入了响应式的类一般是没有引入的
  56. if (reactiveStreamsPresent && new ReactiveResultHandler().subscribeToPublisher(result)) {
  57. if (logger.isTraceEnabled()) {
  58. logger.trace("Adapted to reactive result: " + result);
  59. }
  60. }
  61. //判断是否是CompletionStage类型,该结果用于异步计算,一般不是
  62. else if (result instanceof CompletionStage) {
  63. ((CompletionStage<?>) result).whenComplete((event, ex) -> {
  64. if (ex != null) {
  65. handleAsyncError(ex);
  66. } else if (event != null) {
  67. publishEvent(event);
  68. }
  69. });
  70. }
  71. //判断是否是ListenableFuture类型,如果是,那么执行回调
  72. else if (result instanceof ListenableFuture) {
  73. ((ListenableFuture<?>) result).addCallback(this::publishEvents, this::handleAsyncError);
  74. } else {
  75. //最后将结果作为事件发布
  76. publishEvents(result);
  77. }
  78. }
  79. /**
  80. * ApplicationListenerMethodAdapter的方法
  81. * <p>
  82. * 处理普通返回值
  83. */
  84. private void publishEvents(Object result) {
  85. //如果是数组类型
  86. if (result.getClass().isArray()) {
  87. //那么将每一个元素作为一个事件依次发布
  88. Object[] events = ObjectUtils.toObjectArray(result);
  89. for (Object event : events) {
  90. publishEvent(event);
  91. }
  92. }
  93. //如果是Collection类型
  94. else if (result instanceof Collection<?>) {
  95. //那么将每一个元素作为一个事件依次发布
  96. Collection<?> events = (Collection<?>) result;
  97. for (Object event : events) {
  98. publishEvent(event);
  99. }
  100. } else {
  101. //如果是其它类型,那么将返回值作为事件直接发布
  102. publishEvent(result);
  103. }
  104. }
  105. /**
  106. * ApplicationListenerMethodAdapter的方法
  107. * <p>
  108. * 发布事件
  109. */
  110. private void publishEvent(@Nullable Object event) {
  111. //要求事件不为null
  112. if (event != null) {
  113. Assert.notNull(this.applicationContext, "ApplicationContext must not be null");
  114. //发布事件
  115. this.applicationContext.publishEvent(event);
  116. }
  117. }

6 总结

  本我们学习了Spring事件发布机制的整体流程源码,包括:

  1. initApplicationEventMulticaster初始化事件广播器;
  2. registerListeners、ApplicationListenerDetector注册事件监听器;
  3. EventListenerMethodProcessor解析@EventListener注解;
  4. publishEvent发布事件;

  其中前三点是在IoC容器初始化的过程中一并完成的,最后一点则可以由开发人员手动调用。因此想要比较清晰的弄懂它们的源码原理,还需要对IoC容器初始化的流程有大概了解,特别是那些扩展接口以及回调方法的回调时机,IoC容器的初始化我们在此前的文章中就讲过了。
  Spring的事件发布机制并不会为@EventListener方法对应的bean创建代理对象,而是将对应的@EventListener通过适配器模式转换为监听器适配器进而独立调用。

  在使用Spring事件发布机制时,还需要注意可能抛出的异常:

  1. 如果要执行的方法是私有的,并且方法不是静态的,并且当前类型是一个Spring通用的SpringProxy代理类型,那么将会抛出IllegalStateException异常:“Need to invoke method ‘%s’ found on proxy for target class ‘%s’ but cannot……”。

    1. 普通Spring AOP、事务、@Async等创建的代理都是SpringProxy类型,而@Configuration代理就不是SpringProxy类型。
  2. 如果当前类型是JDK代理,并且方法不是从代理类实现的接口中实现的,那么该方法无法被代理对象调用到,因此同样会抛出异常IllegalStateException异常:“Need to invoke method ‘%s’ declared on target class ‘%s’,……”。

    1. 比如@EventListener方法位于接口的实现类中,但是这个方法是该实现类自己的,那么在启动时就会抛出该异常!

相关文章:
  https://spring.io/
  Spring Framework 5.x 学习
  Spring Framework 5.x 源码

如有需要交流,或者文章有误,请直接留言。另外希望点赞、收藏、关注,我将不间断更新各种Java学习博客!

发表评论

表情:
评论列表 (有 0 条评论,565人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Ribbon深度

    什么是Ribbon Ribbon是Netflix公司开源的一个负载均衡的项目,它属于上述的第二种,是一个客户端负载均衡器,运行在客户端上。它是一个经过了云端测试的IPC库