自动配置原理简单剖析
从@SpringBootApplicaiton注解下手
SpringBootApplication注解包含@EnableAutoConfiguration注解,字面意思启用自动配置
EnableAutoConfiguration注解包含@Import注解且有一个class参数AutoConfigurationImportSelector.class
紧接着进入AutoConfigurationImportSelector类的getAutoConfigurationEntry方法
getAutoConfigurationEntry方法其中getCandidateConfigurations方法是去读取jar中的META-INF/spring.factories文件
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
//
AnnotationAttributes attributes = getAttributes(annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
//去重功能
configurations = removeDuplicates(configurations);
//排除自动配置类,这些类不启用自动配置
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
//过滤不满足的自动配置类,保留有效的自动配置类;可以理解为保留当前maven项目的pom文件中引入了的Spring Boot Starter依赖
configurations = getConfigurationClassFilter().filter(configurations);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
Spring Boot注解先后顺序高至低
1.@SpringBootApplication
2.@EnableAutoConfigurationx
3.@Import(AutoConfigurationImportSelector.class)
4.AutoConfigurationImportSelector类的getImportGroup方法
org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getImportGroup,方法中返回值是AutoConfigurationGroup.class
5.最终会走到AutoConfigurationGroup类的process方法中,处理自动配置核心逻辑
org.springframework.boot.autoconfigure.AutoConfigurationImportSelector.AutoConfigurationGroup#process
6.调用AutoConfigurationImportSelector类的getAutoConfigurationEntry方法获取所有的有效自动配置类org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getAutoConfigurationEntry
7.AutoConfigurationImportSelector类的getCandidateConfigurations方法:读取到所有的自动配置类
org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getCandidateConfigurations
8.SpringFactoriesLoader类的loadFactoryNames方法:读取所有jar包中的spring.factories文件(此文件在META-INF文件夹下),这个文件定义了很多自动配置类
9.根据@EnableAutoConfiguration注解的名字在spring.factories文件中获取key是“org.springframework.boot.autoconfigure.EnableAutoConfiguration”的value值,也就是类名称
org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames
转载:https://blog.csdn.net/weixin_37961431/article/details/116404735