SpringBoot自动装配原理剖析(自己理解,有错请指出)

2023-07-11,,

注解

主类 @SpringBootApplication

@EnableAutoConfiguration

@Import({AutoConfigurationImportSelector.class})

@Import({AutoConfigurationImportSelector.class})

通过 selectImports方法读取META-INF 文件夹下的 spring.factories文件中的全限定类名,返回得到字符串数组,这样就完成了springboot的自动加载
点击查看代码
 public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}

selectImports 方法原理剖析

1.得到注解中的所有属性信息{excludeName=[], exclude=[]}

2.加载META-INF/spring-autoconfigure-metadata.properties,获取所有支持自

动配置的信息

3.去除不需要的

4.然后使用AutoConfigurationImportFilter进行过滤,过滤的方式基本上是判断现有系统是否引入了某个组件,(系统是否使用哪个组件是在pom定义的时候就确定了的)。总而言之,此过滤器会检查候选配置类的注解@ConditionalOnClass,如果要求的类在classpath 中不存在,则这个候选配置类会被排除掉

5.现在已经找到所有需要被应用的候选配置类

SpringBoot自动装配原理剖析(自己理解,有错请指出)的相关教程结束。

《SpringBoot自动装配原理剖析(自己理解,有错请指出).doc》

下载本文的Word格式文档,以方便收藏与打印。