springboot version(v2.7.8)
启动类
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
1 点击 SpringBootApplication
进入,@EnableAutoConfiguration 开启自动配置
2点击 @EnableAutoConfiguration
利用AutoConfigurationImportSelector给容器导入一些组件,导入哪些组件那?点击AutoConfigurationImportSelector 进入;
3 进入 AutoConfigurationImportSelector.class
查看selectImports方法内容
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
4 打开 this.getAutoConfigurationEntry(annotationMetadata);
5打开 getAutoConfigurationEntry
6 进入 getCandidateConfigurations
7 进入SpringFactoriesLoader.loadFactoryNames
8进入 (List)loadSpringFactories,看到装载资源。
9 扫描:META-INF/spring.factories
Enumeration urls = classLoader.getResources("META-INF/spring.factories");
扫描这个目录的作用是:把扫描到的这些文件的内容包装成properties对象
返给spring 容器我们要加载的组件;
10 回头看 7 .loadFactoryNames传入的第一个参数 this.getSpringFactoriesLoaderFactoryClass
11 进入getSpringFactoriesLoaderFactoryClass;
12 EnableAutoConfiguration,这里的作用是:
从properties 中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把它们添加到容器中。第9方法尾部部分;