@SpringBootApplication->
@EnableAutoConfiguration->
@Import({AutoConfigurationImportSelector.class})->
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
public String[] selectImports(AnnotationMetadata annotationMetadata) { if (!this.isEnabled(annotationMetadata)) { return NO_IMPORTS; } else { AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader); AnnotationAttributes attributes = this.getAttributes(annotationMetadata); Listconfigurations = this.getCandidateConfigurations(annotationMetadata, attributes); configurations = this.removeDuplicates(configurations); Set exclusions = this.getExclusions(annotationMetadata, attributes); this.checkExcludedClasses(configurations, exclusions); configurations.removeAll(exclusions); configurations = this.filter(configurations, autoConfigurationMetadata); this.fireAutoConfigurationImportEvents(configurations, exclusions); return StringUtils.toStringArray(configurations); } } }
类的selectImports()方法中的
this.getCandidateConfigurations(annotationMetadata, attributes);
中的
SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
->
SpringFactoriesLoader的
public static ListloadFactoryNames(Class> factoryClass, @Nullable ClassLoader classLoader) { String factoryClassName = factoryClass.getName(); return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList()); };的
Map> loadSpringFactories(@Nullable ClassLoader classLoader)中的
classLoader.getResources("META-INF/spring.factories");
根据这个文件中的value将对应的类加载到IOC容器中,其中会根据
spring-autoconfigure-metadata.properties
中的过滤规则,决定哪些可以加载。
首先说明下,这个 spring-autoconfigure-metadata.properties 文件存储的是”待自动装配候选类“过滤的计算规则,这个信息很重要,框架会根据里面的规则逐一对候选类进行计算看是否需要被自动装配进容器,并不是全部加载;
spring-autoconfigure-metadata.properties 内容格式 (自动配置的类全名.条件Condition=值):
org.springframework.boot.autoconfigure.amqp.RabbitAnnotationDrivenConfiguration.ConditionalOnClass=
final class AutoConfigurationMetadataLoader { protected static final String PATH = "META-INF/spring-autoconfigure-metadata.properties"; private AutoConfigurationMetadataLoader() { } public static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader) { return loadMetadata(classLoader, "META-INF/spring-autoconfigure-metadata.properties"); }
参考:【SpringBoot】-自定义Spring boot Starter(原理、面试问题、代码实现) - 知乎
Spring面试题:SpringBoot开发自定义starter
Springboot自动装配之spring-autoconfigure-metadata.properties和spring.factories(SPI机制核心)_万物皆字节的博客-CSDN博客_spring-autoconfigure-metadata