【SpringBoot】配置加载


title: 【SpringBoot】配置加载
date: 2017-09-18 22:14:15
tags:

  • Java
  • Spring
    categories: Spring

前面的文章已经基本讲清楚从 Spring Boot 应用完整的启动过程了,不过中间过程缺少自动配置相关的功能实现说明。

我把功能配置分为两个部分:

  • 自动化配置
  • 条件注解

以上两个功能极大的简化了 Spring Boot 应用的配置

自动化配置

要弄清自动化配置的起源就得从入口类的 SpringBootApplication 注解说起:

@EnableAutoConfiguration
public @interface SpringBootApplication {
  // 省略注解的字段,别名
}

SpringBootApplication 作为一个组合注解,配置的功能是其核心功能,这部分功能由 EnableAutoConfiguration 注解实现。 EnableAutoConfiguration 也是个符合注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
    Class<?>[] exclude() default {};
    String[] excludeName() default {};
}

EnableAutoConfiguration 的关键是导入了 EnableAutoConfigurationImportSelector ,这类继承自 AutoConfigurationImportSelector。在 Spring 容器刷新的过程中的 invokeBeanFactoryPostProcessors 方法会调用到 EnableAutoConfigurationImportSelector 的逻辑:

// EnableAutoConfigurationImportSelector
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
   if (!isEnabled(annotationMetadata)) {
      return NO_IMPORTS;
   }
   try {
      // 获取注解属性
      AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
            .loadMetadata(this.beanClassLoader);
      AnnotationAttributes attributes = getAttributes(annotationMetadata);
      // 读取spring.factories属性文件中的数据
      List<String> configurations = getCandidateConfigurations(annotationMetadata,
            attributes);
      // 删除重复的配置类
      configurations = removeDuplicates(configurations);
      configurations = sort(configurations, autoConfigurationMetadata);
      // 找到@EnableAutoConfiguration注解中定义的需要被过滤的配置类
      Set<String> exclusions = getExclusions(annotationMetadata, attributes);
      checkExcludedClasses(configurations, exclusions);
      // 删除这些需要被过滤的配置类
      configurations.removeAll(exclusions);
      configurations = filter(configurations, autoConfigurationMetadata);
      fireAutoConfigurationImportListeners(configurations, exclusions);
      // 返回最终得到的自动化配置类
      return configurations.toArray(new String[configurations.size()]);
   }
   catch (IOException ex) {
      throw new IllegalStateException(ex);
   }
}

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
      AnnotationAttributes attributes) {
   // 调用SpringFactoriesLoader的loadFactoryNames静态方法
   // getSpringFactoriesLoaderFactoryClass方法返回的是EnableAutoConfiguration类对象
   List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
         getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
   Assert.notEmpty(configurations,
         "No auto configuration classes found in META-INF/spring.factories. If you "
               + "are using a custom packaging, make sure that file is correct.");
   return configurations;
}

EnableAutoConfigurationImportSelector 会使用 SpringFactoriesLoader 加载相应的配置

// SpringFactoriesLoader 
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
   // 解析出properties文件中需要的key值
   String factoryClassName = factoryClass.getName();
   try {
      // 常量FACTORIES_RESOURCE_LOCATION的值为META-INF/spring.factories
      // 使用类加载器找META-INF/spring.factories资源
      Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
            ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
      List<String> result = new ArrayList<String>();
      while (urls.hasMoreElements()) {
         URL url = urls.nextElement();
         Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
         String factoryClassNames = properties.getProperty(factoryClassName);
         result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
      }
      return result;
   }
   catch (IOException ex) {
      throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
            "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
   }
}

条件注解

条件注解实现

以常见的 ConditionalOnClass 注解为例:

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnClassCondition.class)
public @interface ConditionalOnClass {
   Class<?>[] value() default {};  // 要匹配的类
   String[] name() default {};  // 要匹配的类名
}

必要重要的是 Conditional 注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Conditional {
   Class<? extends Condition>[] value();
}

从命名可以看出 Conditional 注解的 value 属性是具体的 Condition 实现,Spring Boot 提供了通用的 Condition 抽象类: SpringBootCondition,其完成了具体匹配逻辑之外的其他模板:

// SpringBootCondition

@Override
public final boolean matches(ConditionContext context,
      AnnotatedTypeMetadata metadata) {
   // 获得类名或方法名
   String classOrMethodName = getClassOrMethodName(metadata);
   try {
      // 抽象方法由子类实现匹配逻辑
      // 返回结构包装了匹配结果和log信息
      ConditionOutcome outcome = getMatchOutcome(context, metadata);
      // log
      logOutcome(classOrMethodName, outcome);
      // 报告一下
      recordEvaluation(context, classOrMethodName, outcome);
      // 返回匹配结果
      return outcome.isMatch();
   }
   catch // 省略异常处理
}

具体到 ConditionalOnClass 使用的是 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()) {
         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 注解的属性
   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));
   }
   // 返回全部匹配成功的ConditionalOutcome
   return ConditionOutcome.match(matchMessage);
}

条件注解激活

这里又要从 Spring 容器的 refresh 方法说起了,这个方法太重要了。其中的 invokeBeanFactoryPostProcessors 方法调用 BeanFactoryPostProcessor 和 BeanDefinitionRegistryPostProcessor 的处理逻辑,在 bean 实例化阶段开始之前,对注册到容器的 BeanDefinition 保存的原始数据做出修改。与条件注解激活有关的 posstProcessor 是 ConfigurationClassPostProcessor,其实现自 BeanFactoryPostProcessor 。

ConfigurationClassPostProcessor 会从 BeanFactory 中找出所有被 @Configuration 直接或间接注解的类(包括 @Component, @ComponentScan, @Import, @ImportResource 修饰的类)进行解析。对解析的结果使用 ConditionEvaluator 进行过滤判断。判断逻辑:

public boolean shouldSkip(AnnotatedTypeMetadata metadata, ConfigurationPhase phase) {
   // 
   if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
      return false;
   }

   if (phase == null) {
      if (metadata instanceof AnnotationMetadata &&
            ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
         return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
      }
      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) {
         if (!condition.matches(this.context, metadata)) {
            return true;
         }
      }
   }

   return false;
}

其中 ConfigurationCondition 是 Condition 的子接口,内部主要定义了枚举类型表示条件注解生效的阶段:

public interface ConfigurationCondition extends Condition {
   ConfigurationPhase getConfigurationPhase();
   enum ConfigurationPhase {
      PARSE_CONFIGURATION,
      REGISTER_BEAN
   }
}

完整的 ConfigurationClassPostProcessor 处理逻辑:

configuration-annotation-process.png

参考:SpringBoot源码分析之Spring容器的refresh过程

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念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

推荐阅读更多精彩内容