27-Spring Boot 注解开关原理
Spring 注解开关原理
1. 如果完成自动化配置
- 定义一个Annotation,让使用了这个Annotaion的应用程序自动化地注入一些类或者做一些底层的事情。
- 我们使用
@Import注解配合一个配置类来完成上面的事情。 - 最简单的注解:
EnableContentService,使用这个注解的程序会自动注入ContentService这个Bean
1 | |
- 之后在应用程序入口使用
@EnableContentService注解,Spring Boot使用了ImportSelector来完成
2. ImportSelector的使用
- 修改
@EnableContentService注解,添加属性policy,并且import一个Selector
1 | |
- 这个
ContentImportSelector根据EnableContentService注解里的policy加载不同的bean:也就是policy如果是core,则会加载CoreContentService,否则会加载SimpleContentService
1 | |
2.1. CoreContentService
1 | |
2.2. CoreContentConfiguration
1 | |
3. ImportSelector在Spring Boot中使用
- SpringBoot里的
ImportSelector是通过SpringBoot提供的@EnableAutoConfiguration这个注解里完成的。 - 这个
@EnableAutoConfiguration注解可以显式地调用,否则它会在@SpringBootApplication注解中隐式地被调用。 @EnableAutoConfiguration注解中使用了EnableAutoConfigurationImportSelector作为ImportSelector。下面这段代码就是EnableAutoConfigurationImportSelector中进行选择的具体代码:
1 | |
- 其中
getCandidateConfigurations方法将获取配置类:
1 | |
SpringFactoriesLoader.loadFactoryNames方法会根据FACTORIES_RESOURCE_LOCATION这个静态变量从所有的jar包中读取META-INF/spring.factories文件信息:
1 | |
getCandidateConfigurations方法中的getSpringFactoriesLoaderFactoryClass方法返回的是EnableAutoConfiguration.class,所以会过滤出key为org.springframework.boot.autoconfigure.EnableAutoConfiguration的值。- 之后根据文件内容进行配置初始化
4. 参考
27-Spring Boot 注解开关原理
https://spricoder.github.io/2022/04/13/Spring-Boot/27-Spring-Boot-%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%85%B3%E5%8E%9F%E7%90%86/