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