文章目錄
- 一、寫在前面
- 二、使用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