Spring-Context注解源码之@EventListener

开发 前端
EventListenerMethodProcessor的processBean方法中,会遍历已经注册的所有的bean,找到包含有被 @EventListener 标注的方法。这些方法会被遍历已经创建的 EventListenerFactory 找到合适的工厂来生成 applicationListener,并将 applicationListener 注册到容器的事件监听器列表。

[[410307]]

 注解说明

Annotation that marks a method as a listener for application events.

以注解的方式将一个方法标记为事件监听器。如果对于spring事件监听机制还不了解的小伙伴点击查看一文彻底搞懂spring事件监听机制

属性说明

  1. public @interface EventListener { 
  2.  
  3.    /** 
  4.     * 同class 
  5.     */ 
  6.    @AliasFor("classes"
  7.    Class<?>[] value() default {}; 
  8.  
  9.    /** 
  10.     * 监听事件的类型 
  11.     * 如果这个属性长度不为空,则以这个属性的为准 
  12.     * 如果这个属性长度为空,则以被标注方法的参数为准 
  13.     */ 
  14.    @AliasFor("value"
  15.    Class<?>[] classes() default {}; 
  16.  
  17.    /** 
  18.     * 以spring表达的方式计算事件监听是否需要触发 
  19.     */ 
  20.    String condition() default ""
  21.  

通过上述属性,我们可以发现,相比起实现接口的方式创建事件监听器,用注解的方式灵活性更加大,不仅可以指定多个接受事件类型,还可以增加是否触发的条件。

使用示例

  1. @EventListener 
  2. public void customListener1(MyEvent event) { 
  3.     System.out.println("接受事件customListener1"); 

相关源码

EventListenerMethodProcessor

  1. /** 
  2.  * 检测bean里面是否包含 @EventListener 
  3.  */ 
  4. private void processBean(final String beanName, final Class<?> targetType) { 
  5.    if (!this.nonAnnotatedClasses.contains(targetType) && 
  6.          !targetType.getName().startsWith("java") && 
  7.          !isSpringContainerClass(targetType)) { 
  8.  
  9.       Map<Method, EventListener> annotatedMethods = null
  10.       try { 
  11.          // 找到所有包含 @EventListener 的方法 
  12.          annotatedMethods = MethodIntrospector.selectMethods(targetType, 
  13.                (MethodIntrospector.MetadataLookup<EventListener>) method -> 
  14.                      AnnotatedElementUtils.findMergedAnnotation(method, EventListener.class)); 
  15.       } 
  16.       catch (Throwable ex) { 
  17.          // An unresolvable type in a method signature, probably from a lazy bean - let's ignore it. 
  18.          if (logger.isDebugEnabled()) { 
  19.             logger.debug("Could not resolve methods for bean with name '" + beanName + "'", ex); 
  20.          } 
  21.       } 
  22.  
  23.       if (CollectionUtils.isEmpty(annotatedMethods)) { 
  24.          // 如果这个类一个包含 @EventListener 方法都没有则缓存到 nonAnnotatedClasses 中,减少重复计算 
  25.          this.nonAnnotatedClasses.add(targetType); 
  26.          if (logger.isTraceEnabled()) { 
  27.             logger.trace("No @EventListener annotations found on bean class: " + targetType.getName()); 
  28.          } 
  29.       } 
  30.       else { 
  31.          // Non-empty set of methods 
  32.          ConfigurableApplicationContext context = this.applicationContext; 
  33.          Assert.state(context != null"No ApplicationContext set"); 
  34.          // 可以创建自定义 EventListenerFactory,如果不创建,默认拥有 DefaultEventListenerFactory 
  35.          List<EventListenerFactory> factories = this.eventListenerFactories; 
  36.          Assert.state(factories != null"EventListenerFactory List not initialized"); 
  37.          for (Method method : annotatedMethods.keySet()) { 
  38.             for (EventListenerFactory factory : factories) { 
  39.                // 对于每一个方法遍历所有的工厂,找到一个支持的工厂就进入创建并完成遍历 
  40.                if (factory.supportsMethod(method)) { 
  41.                   // 根据方法创建 applicationListener,并将 applicationListener 添加给容器 
  42.                   Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName)); 
  43.                   ApplicationListener<?> applicationListener = 
  44.                         factory.createApplicationListener(beanName, targetType, methodToUse); 
  45.                   if (applicationListener instanceof ApplicationListenerMethodAdapter) { 
  46.                      ((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator); 
  47.                   } 
  48.                   context.addApplicationListener(applicationListener); 
  49.                   break; 
  50.                } 
  51.             } 
  52.          } 
  53.          if (logger.isDebugEnabled()) { 
  54.             logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" + 
  55.                   beanName + "': " + annotatedMethods); 
  56.          } 
  57.       } 
  58.    } 

EventListenerMethodProcessor的processBean方法中,会遍历已经注册的所有的bean,找到包含有被 @EventListener 标注的方法。这些方法会被遍历已经创建的 EventListenerFactory 找到合适的工厂来生成 applicationListener,并将 applicationListener 注册到容器的事件监听器列表。

ApplicationListenerMethodAdapter

  1. /** 
  2.  * 解析时间监听器支持的事件类型 
  3.  */ 
  4. private static List<ResolvableType> resolveDeclaredEventTypes(Method method, @Nullable EventListener ann) { 
  5.    int count = method.getParameterCount(); 
  6.    if (count > 1) { 
  7.       // 如果方法本身参数超过1个,则直接抛出异常 
  8.       throw new IllegalStateException( 
  9.             "Maximum one parameter is allowed for event listener method: " + method); 
  10.    } 
  11.  
  12.    if (ann != null) { 
  13.       // 取出 注解中的 classes属性 
  14.       Class<?>[] classes = ann.classes(); 
  15.       if (classes.length > 0) { 
  16.          // 如果classes属性不为空,则解析classes属性并返回作为事件解析类型 
  17.          List<ResolvableType> types = new ArrayList<>(classes.length); 
  18.          for (Class<?> eventType : classes) { 
  19.             types.add(ResolvableType.forClass(eventType)); 
  20.          } 
  21.          return types; 
  22.       } 
  23.    } 
  24.  
  25.    // 如果传入的classes属性为空,并且方法没有参数,也抛出异常 
  26.    if (count == 0) { 
  27.       throw new IllegalStateException( 
  28.             "Event parameter is mandatory for event listener method: " + method); 
  29.    } 
  30.    return Collections.singletonList(ResolvableType.forMethodParameter(method, 0)); 

ApplicationListenerMethodAdapter的resolveDeclaredEventTypes方法会解析@EventListener标签的classes属性,然后根据这个属性决定事件监听器的监听的事件类型。

如果方法参数个数超过1个,直接抛出异常。这是一个事件触发以后,如果接受的方法参数个数大于1个,spring没办法给方法进行传参。

如果classes属性为空,并且方法参数个数为0个,也抛出异常。这是因为spring无法推断这个监听器需要支持什么类型的事件。

除去上面两种情况,解析都是成功,同时classes属性会优先被选择为监听的事件类型。

  1. private boolean shouldHandle(ApplicationEvent event, @Nullable Object[] args) { 
  2.    if (args == null) { 
  3.       return false
  4.    } 
  5.    String condition = getCondition(); 
  6.    if (StringUtils.hasText(condition)) { 
  7.      // 如果 condition 属性不为空,则进行spring表达式计算结果并返回 
  8.       Assert.notNull(this.evaluator, "EventExpressionEvaluator must not be null"); 
  9.       return this.evaluator.condition( 
  10.             condition, event, this.targetMethod, this.methodKey, args, this.applicationContext); 
  11.    } 
  12.    return true

ApplicationListenerMethodAdapter的shouldHandle方法会根据@EventListener标签的condition属性判断是否需要推送消息。

如果condition不为空,则使用spring表达式计算condition得到结果,结果为true的时候才推送事件。如果condition为空,则不判断直接推送。

责任编辑:武晓燕 来源: 今日头条
相关推荐

2023-04-10 11:00:00

注解Demo源码

2022-02-20 07:28:13

Spring注解用法

2023-07-10 08:43:53

SpringIDEA

2022-02-19 07:41:36

Bean注解项目

2022-12-07 08:02:43

Spring流程IOC

2022-06-09 07:27:14

JavaSpring容器

2022-05-30 11:17:44

Spring容器配置

2020-12-20 10:02:17

ContextReactrender

2019-09-09 06:30:06

Springboot程序员开发

2023-05-08 08:11:49

@Component使用场景时序图

2023-06-02 16:24:46

SpringBootSSM

2011-04-15 09:44:45

Spring

2009-06-15 17:48:32

Spring注解注入属性

2021-08-27 07:38:21

AndroidDialogContext

2020-10-14 06:23:54

SpringBean实例化

2021-03-08 00:11:02

Spring注解开发

2017-08-02 14:44:06

Spring Boot开发注解

2021-03-11 11:14:39

鸿蒙HarmonyOS应用

2023-05-05 07:39:04

Spring事务面试

2022-06-07 07:58:45

SpringSpring AOP
点赞
收藏

51CTO技术栈公众号