Sping Boot自动装配原理
- 在 SpringBoot 的启动类上有一个
@SpringBootApplication
注解,这个注解里有一个@EnableAutoConfiguration
注解; @EnableAutoConfiguration
注解通过@Import
导入了一个AutoConfigurationImportSelector
类,该类实现了ImportSelector
接口,实现了selectImports()
方法,该方法会返回需要自动装配到 Spring 容器中的类的名称;- 再看
selectImports()
方法,该方法只要有三步:getCandidateConfigurations
方法获取所有的 Bean;- 获取
@EnableAutoConfiguration
注解中 execlude 指定的不需要自动装配的类; - 返回a中去掉b中的类。
主要看getCandidateConfigurations()
方法,该方法里有一个loadFactoryNames()
方法,这个方法读取依赖中 META-INF 目录下的 spring.factories 文件,获取 spring.factories 文件中 EnableAutoConfiguration 配置下所有要自动装配的类的名称并返回。