【SpringBoot】条件注解


title: 【SpringBoot】条件注解
date: 2017-12-08 20:45:21
tags:

  • Java
  • Spring
    categories: Spring

条件注解

ConditionOnClass

以 ConditionOnClass 为例分析:

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {

   // The classes that must be present.
   Class<?>[] value() default {};

   // The classes names that must be present.
   String[] name() default {};

}

ConditionOnClass 注解使用 Conditional 注解修饰:

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
  
   // All Conditions that must match in order for the component to be registered.
   Class<? extends Condition>[] value();
}

Conditional 定义了一个条件数组 Condition[],条件的定义:

public interface Condition {
   boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}

看一下上面 Conditional 注解使用的 OnClassCondition。

首先其继承于 SpringBootCondition,SpringBoot 中条件注解都继承这个抽象类:

public abstract class SpringBootCondition implements Condition {

   @Override
   public final boolean matches(ConditionContext context,
         AnnotatedTypeMetadata metadata) {
      // 得到类名或者方法名(条件注解可以作用的类或者方法上)
      String classOrMethodName = getClassOrMethodName(metadata);
      try {
         // 抽象方法,具体子类实现
         // ConditionOutcome记录了匹配结果boolean和log信息
         ConditionOutcome outcome = getMatchOutcome(context, metadata);
         // log记录一下匹配信息
         logOutcome(classOrMethodName, outcome);
         // 报告记录一下匹配信息
         recordEvaluation(context, classOrMethodName, outcome);
         return outcome.isMatch();
      }
      catch (...) {
        // ...
      }
   }

   // 省略其他
}

OnClassCondition 实现:

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
      AnnotatedTypeMetadata metadata) {
   ClassLoader classLoader = context.getClassLoader();
   ConditionMessage matchMessage = ConditionMessage.empty();
   // 得到 @ConditionalOnClass 注解的类
   List<String> onClasses = getCandidates(metadata, ConditionalOnClass.class);
   if (onClasses != null) {
      // 如果类存在
      // 得到在类加载器中不存在的类
      List<String> missing = getMatches(onClasses, MatchType.MISSING, classLoader);
      if (!missing.isEmpty()) {
         // 如果存在类加载器中不存在对应的类,返回一个匹配失败的 ConditionalOutcome
         return ConditionOutcome
               .noMatch(ConditionMessage.forCondition(ConditionalOnClass.class)
                     .didNotFind("required class", "required classes")
                     .items(Style.QUOTE, missing));
      }
      // 如果类加载器中有所有的对应类,匹配信息进行记录
      matchMessage = matchMessage.andCondition(ConditionalOnClass.class)
            .found("required class", "required classes").items(Style.QUOTE,
                  getMatches(onClasses, MatchType.PRESENT, classLoader));
   }
   // 对@ConditionalOnMissingClass注解做相同的逻辑处理
   // @ConditionalOnClass和@ConditionalOnMissingClass可以一起使用
   List<String> onMissingClasses = getCandidates(metadata,
         ConditionalOnMissingClass.class);
   if (onMissingClasses != null) {
      List<String> present = getMatches(onMissingClasses, MatchType.PRESENT,
            classLoader);
      if (!present.isEmpty()) {
         return ConditionOutcome.noMatch(
               ConditionMessage.forCondition(ConditionalOnMissingClass.class)
                     .found("unwanted class", "unwanted classes")
                     .items(Style.QUOTE, present));
      }
      matchMessage = matchMessage.andCondition(ConditionalOnMissingClass.class)
            .didNotFind("unwanted class", "unwanted classes").items(Style.QUOTE,
                  getMatches(onMissingClasses, MatchType.MISSING, classLoader));
   }
   return ConditionOutcome.match(matchMessage);
}

ConditionalOnBean

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
   // 匹配的bean类型
   Class<?>[] value() default {};

   // 匹配的bean类型的类名
   String[] type() default {};

   // 匹配的bean注解
   Class<? extends Annotation>[] annotation() default {};

   // 匹配的bean的名字
   String[] name() default {};

   // 搜索策略
   // CURRENT(只在当前容器中找)
   // PARENTS(只在所有的父容器中找;但是不包括当前容器)
   // ALL(CURRENT和PARENTS的组合)
   SearchStrategy search() default SearchStrategy.ALL;
}

OnBeanCondition 实现:

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
      AnnotatedTypeMetadata metadata) {
   ConditionMessage matchMessage = ConditionMessage.empty();
   if (metadata.isAnnotated(ConditionalOnBean.class.getName())) {
      // 针对 @ConditionalOnBean 注解
      // 构造一个BeanSearchSpec,会从@ConditionalOnBean注解中获取属性,然后设置到BeanSearchSpec中
      BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
            ConditionalOnBean.class);
      // 从BeanFactory中根据策略找出所有匹配的bean
      List<String> matching = getMatchingBeans(context, spec);
      if (matching.isEmpty()) {
         // 如果没有匹配的bean,返回一个没有匹配成功的ConditionalOutcome
         return ConditionOutcome.noMatch(
               ConditionMessage.forCondition(ConditionalOnBean.class, spec)
                     .didNotFind("any beans").atAll());
      }
      // 如果找到匹配的bean,匹配信息进行记录
      matchMessage = matchMessage.andCondition(ConditionalOnBean.class, spec)
            .found("bean", "beans").items(Style.QUOTE, matching);
   }
   if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
      // 相同的逻辑,针对@ConditionalOnSingleCandidate注解
      BeanSearchSpec spec = new SingleCandidateBeanSearchSpec(context, metadata,
            ConditionalOnSingleCandidate.class);
      List<String> matching = getMatchingBeans(context, spec);
      if (matching.isEmpty()) {
         return ConditionOutcome.noMatch(ConditionMessage
               .forCondition(ConditionalOnSingleCandidate.class, spec)
               .didNotFind("any beans").atAll());
      }
      else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matching,
            spec.getStrategy() == SearchStrategy.ALL)) {
         // 多了一层判断,判断是否只有一个bean
         return ConditionOutcome.noMatch(ConditionMessage
               .forCondition(ConditionalOnSingleCandidate.class, spec)
               .didNotFind("a primary bean from beans")
               .items(Style.QUOTE, matching));
      }
      matchMessage = matchMessage
            .andCondition(ConditionalOnSingleCandidate.class, spec)
            .found("a primary bean from beans").items(Style.QUOTE, matching);
   }
   if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
      // 相同的逻辑,针对 @ConditionalOnMissingBean 注解
      BeanSearchSpec spec = new BeanSearchSpec(context, metadata,
            ConditionalOnMissingBean.class);
      List<String> matching = getMatchingBeans(context, spec);
      if (!matching.isEmpty()) {
         return ConditionOutcome.noMatch(ConditionMessage
               .forCondition(ConditionalOnMissingBean.class, spec)
               .found("bean", "beans").items(Style.QUOTE, matching));
      }
      matchMessage = matchMessage.andCondition(ConditionalOnMissingBean.class, spec)
            .didNotFind("any beans").atAll();
   }
   return ConditionOutcome.match(matchMessage);
}

条件注解激活

【Spring】容器刷新 中 invokeBeanFactoryPostProcessors 方法会处理 BeanDefinitionRegistryPostProcessor 和 BeanDefinitionRegistryPostProcessor 的实现。其中 ConfigurationClassPostProcessor 是最低优先级执行的 BeanDefinitionRegistryPostProcessor。

ConfigurationClassPostProcessor 会使用 ConfigurationClassParser 的 ConditionEvaluator 解析所有 @Configuration 注解的bean。

ConfigurationClassParser 使用 ConditionEvaluator 解析:

if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(),
                                       ConfigurationPhase.PARSE_CONFIGURATION)) {
  return;
}

ConditionEvaluator的 shouldSkip 方法:

public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {
   // 如果这个类没有被@Conditional注解所修饰,不会skip
   if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
      return false;
   }
   // 如果参数中沒有设置条件注解的生效阶段
   if (phase == null) {
      // 是配置类的话直接使用PARSE_CONFIGURATION阶段
      if (metadata instanceof AnnotationMetadata &&
            ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
         return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
      }
      // 否则使用REGISTER_BEAN阶段
      return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
   }
   // 获取配置类的条件注解得到条件数据,并添加到集合中
   List<Condition> conditions = new ArrayList<Condition>();
   for (String[] conditionClasses : getConditionClasses(metadata)) {
      for (String conditionClass : conditionClasses) {
         Condition condition = getCondition(conditionClass, this.context.getClassLoader());
         conditions.add(condition);
      }
   }
   // 对条件集合做个排序
   AnnotationAwareOrderComparator.sort(conditions);
   // 遍历条件集合
   for (Condition condition : conditions) {
      ConfigurationPhase requiredPhase = null;
      if (condition instanceof ConfigurationCondition) {
         requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
      }
      // 没有这个解析类不需要阶段的判断或者解析类和参数中的阶段一致才会继续进行
      if (requiredPhase == null || requiredPhase == phase) {
         // 不满足条件返回 true
         if (!condition.matches(this.context, metadata)) {
            return true;
         }
      }
   }
   return false;
}

条件注入激活还是在容器 refresh 过程中,更具体是在 invokeBeanFactoryPostProcessors 方法中解析配置类时,会跳过不满足条件的类。


注解条件使用的 demo:SpringBoot源码分析之条件注解的底层实现

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,478评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,825评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,482评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,726评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,633评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,018评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,168评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,320评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,264评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,288评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,995评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,587评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,909评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,284评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,862评论 2 339

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,712评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,561评论 18 139
  • 1.1 spring IoC容器和beans的简介 Spring 框架的最核心基础的功能是IoC(控制反转)容器,...
    simoscode阅读 6,689评论 2 22
  • 上一篇文章中,我们分析了SpringBoot的启动过程:构造SpringApplication并调用它的run方法...
    丶Format阅读 6,745评论 6 24
  • 那些一开始反对你,后来转而支持你的人,大多是有主见就事论事的人,有利于共同合作。一直支持你的人可能更多是一种精...
    青青三月阅读 150评论 0 0