springboot自动配置原理
springboot的自动配置是因为springboot的核心注解@SpringBootApplication。

该注解是由@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan三个注解复合组成。
其中,@SpringBootConfiguration用于标注这个类是一个配置类;
它只是@Configuration注解的派生注解;
它与@Configuration注解的功能一致;
只不过@SpringBootConfiguration是springboot的注解,而@Configuration是Spring的注解。
@ComponenScan注解用于指定需要扫描的包路径。
所以,springboot自动加载的核心原理在于@EnableAutoConfiguration这一个注解上。

@EnableAutoConfiguration注解由@Import(AutoConfigurationImportSelector.class)和@AutoConfiguration注解复合组成。
其中@AutoConfiguration用于指定包扫描路径规则;
1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、从META-INF/spring.factories位置来加载一个文件。默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
通过在文件中写死所有springboot已启动就要给容器加载的所有配置。
不过虽然springboot虽然所有自动配置启动的时候默认全部加载,但是并不是所有的都会有效,是按照条件装配规则(@Conditional),最终按需配置。
SpringBoot默认会在底层配置好所有的组件,但是如果用户自己配置了则以用户配置的优先。
总结:
● SpringBoot先加载所有的自动配置类 xxxxxAutoConfiguration
● 每个自动配置类按照条件进行生效,默认都会绑定配置文件指定的值。xxxxProperties里面拿。xxxProperties和配置文件进行了绑定
● 生效的配置类就会给容器中装配很多组件
● 只要容器中有这些组件,相当于这些功能就有了
● 若是需要定制化配置,可通过以下两种途径进行配置
○ 用户直接自己@Bean替换底层的组件
○ 用户去看这个组件是获取的配置文件什么值就去修改。
一般流程如下:
xxxxxAutoConfiguration ---> 组件 ---> xxxxProperties里面拿值 ----> application.properties
组件中经常变化的值是从application.properties中来的

浙公网安备 33010602011771号