引导自动加载配置类
1、@SpringBootApplication 等价于 @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
2、@SpringBootConfiguration ~ Configuration
3、@ComponentScan 自动配置扫描文件范围
4、@EnableAutoConfiguration 等价于@AutoConfigurationPackage + @Import(AutoConfigurationImportSelector.class)
5、@AutoConfigurationPackage 等价于 @Import(AutoConfigurationPackages.Registrar.class)
利用Registrar给容器中导入一系列组件,默认将MainApplication所在包下的所有组件导入进来。
6、AutoConfigurationImportSelector.class
(1)利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
(2)调用List configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
(3)利用工厂加载 Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
(4)从META-INF/spring.factories位置来加载一个文件。
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
按需开启自动配置项
虽然我们127个场景的所有自动配置启动的时候默认全部加载(xxxxAutoConfiguration),但仍需按照条件装配规则(@Conditional)按需配置。
总结:
• SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
• 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
• 生效的配置类就会给容器中装配很多组件
• 只要容器中有这些组件,相当于这些功能就有了
• 定制化配置
(1)用户直接自己@Bean替换底层的组件
@Bean
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
}
(2) 用户去看这个组件是获取的配置文件的什么值,可在 application.properties中直接修改。
xxxxxAutoConfiguration —> 组件 —> xxxxProperties里面拿值 ----> application.properties