不推薦使用Spring Boot 2.2.0 ,這個問題你肯定會遇到 (二)
阿新 • • 發佈:2019-12-31
專案推薦: Spring Cloud 、Spring Security OAuth2的RBAC許可權管理系統 歡迎關注 最新版本實踐
上篇文章講到 Spring Boot 2.2.0 和 MyBatis 相容問題,今天再來看一下 這個 boom change
ConfigurationProperties 註解使用
如上圖,當配置檔案中存在相同組的屬性,使用者名稱
、密碼
、年齡
都屬於使用者屬性的抽象,按面向的規則我們可以抽取出一個 User
的PO
型別使用 @ConfigurationProperties
將外部配置繫結到程式碼中的bean。同時可以像其他任何Spring bean一樣在整個應用程式程式碼中注入和使用此bean。
- application.properties
user.username=lengleng
user.password=123456
user.age=26複製程式碼
- User POJO
/**
* @author lengleng
* @date 2019-11-08
* <p>
* 2.2 之前版本,必須使用 @Component 或者 @Configuration 宣告成Spring Bean
*/
@Component
@ConfigurationProperties(prefix = "user")
public class User {
private String username;
private String password;
private Integer age;
...
}複製程式碼
如上程式碼,當我們在使用 spring boot 2.2
之前版本 必須使用 @Component
或者 @Configuration
宣告成Spring Bean,不然無法注入
- 這裡注意下
ConfigurationProperties
和@Value
的區別
ConfigurationPropertiesScan
- 2.2.0 預設開啟此功能
2.2.0
新增一個@ConfigurationPropertiesScan
的註解,預設是開啟的掃描 main 啟動類所在的包路徑的所有ConfigurationProperties
,所以可以不用再加@Component
或者@Configuration
- 2.2.1 預設關閉此功能,需要顯式指定此註解
實際在使用過程中 你會發現@Profile
和這個註解的相容問題,@ConfigurationPropertiesScan not compatible with @Profile @ConfigurationProperties
所以Spring Boot 2.2.1
預設關閉了這個功能
- 2.2.1 預設關閉此功能,需要顯式指定此註解
若想開啟,只需要在 啟動類加上
總結
- 當你從 2.1.X 升級到 2.2 ,肯定不會遇到這個問題,因為預設相容
@Component
掃描的形式 - 如果從 2.2.0 升級到 2.2.1 , 一定要特別小心此處,可能會導致你的配置類全部失效
- 到底加不加,在使用IDEA當前版本 給你提示
IDEA 2019.3 才會正式支援該註解