文章目录
- 一、写在前面
- 二、使用imports文件
- 1、使用
- 2、示例比对
- 3、完整示例
- 参考资料
一、写在前面
spring.factories
是一个位于META-INF/
目录下的配置文件,它基于Java的SPI(Service Provider Interface)机制
的变种实现。
这个文件的主要功能是允许开发者声明接口的实现类,从而实现SpringBoot的自动装配和扩展点注册
。
这个文件在SpringBoot2.7
以前,真就是SpringBoot的扩展神器,各种自动配置的插件几乎都是基于这种方式来实现的。
但是SpringBoot2.7
以后,spring.factories
就不是最优解了,而是替换为了META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
。
具体文档地址:https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.7-Release-Notes#changes-to-auto-configuration
以下是翻译:
简单来说,只需要创建一个META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件,每一行都是一个自动配置的条目即可,用法比以前简洁不少。
而以前的spring.factories
的org.springframework.boot.autoconfigure.EnableAutoConfiguration
键已经被删除了,详情:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide
二、使用imports文件
1、使用
从SpringBoot 3.0开始,引入了基于imports文件的新机制,作为spring.factories
的替代方案。这些文件位于META-INF/spring/
目录下,每种类型的扩展点对应一个专门的文件:
2、示例比对
旧方式(spring.factories):
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.FooAutoConfiguration,\
com.example.BarAutoConfiguration
新方式(AutoConfiguration.imports):
com.example.FooAutoConfiguration
com.example.BarAutoConfiguration
3、完整示例
// 1. 创建配置属性类
@ConfigurationProperties(prefix = "myapp")
publicclass MyProperties {privateboolean enabled = true;private String name = "default";// getter和setter方法// ...
}// 2. 创建自动配置类
@AutoConfiguration// 注意这里使用了@AutoConfiguration而非@Configuration
@EnableConfigurationProperties(MyProperties.class)
@ConditionalOnProperty(prefix = "myapp", name = "enabled", havingValue = "true", matchIfMissing = true)
publicclass MyAutoConfiguration {privatefinal MyProperties properties;public MyAutoConfiguration(MyProperties properties) {this.properties = properties;}@Bean@ConditionalOnMissingBeanpublic MyService myService() {// 根据属性创建服务returnnew MyServiceImpl(properties.getName());}
}
3、然后,在META-INF/spring/
目录下创建org.springframework.boot.autoconfigure.AutoConfiguration.imports
文件:
com.example.MyAutoConfiguration
参考资料
https://mp.weixin.qq.com/s/VQh1xwAhajoPM9I1DnTs1Q