SpringBoot
版本升級(jí)兼容性一直做的不是多么的美麗牍帚,各個(gè)大分支之間由于底層使用的Srping
版本不同,才導(dǎo)致的這種問題出現(xiàn)乳蛾,而升級(jí)到2.2.1.RELEASE
版本之后又遇到一個(gè)配置綁定
的坑履羞。
免費(fèi)教程專題
恒宇少年在博客整理三套免費(fèi)學(xué)習(xí)教程專題
峦萎,由于文章偏多
特意添加了閱讀指南
,新文章以及之前的文章都會(huì)在專題內(nèi)陸續(xù)填充
忆首,希望可以幫助大家解惑更多知識(shí)點(diǎn)爱榔。
問題描述
SpringBoot
在升級(jí)到2.2.1.RELEASE
版本后遇到了屬性配置
綁定的問題,我去找到SpringBoot
版本發(fā)布的頁面(Spring-Boot-2.2-Release-Notes)才了解到從2.2.1.RELEASE
版本開始@SpringBootApplication
注解已經(jīng)不再添加@ConfigurationPropertiesScan
支持糙及,需要手動(dòng)進(jìn)行配置详幽,這一點(diǎn)我們從源碼上可以更清楚的看到。
2.2.0.RELEASE
SpringBoot
2.2.0.RELEASE版本中@SpringBootApplication
注解部分源碼如下所示:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
@ConfigurationPropertiesScan
public @interface SpringBootApplication {
//...
}
通過源碼我們可以看到2.2.0.RELEASE版本的@SpringBootApplication
注解默認(rèn)添加了ConfigurationPropertiesScan
注解浸锨,也就是默認(rèn)開啟了掃描@ConfigurationProperties
注解的配置類唇聘,然后根據(jù)prefix
進(jìn)行屬性綁定。
2.2.1.RELEASE
SpringBoot
2.2.1.RELEASE版本中@SpringBootApplication
注解部分源碼如下所示:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
//...
}
我們發(fā)現(xiàn)在SpringBoot
2.2.1.RELEASE版本的@SpringBootApplication
注解中已經(jīng)不再默認(rèn)添加@ConfigurationPropertiesScan
注解的支持了柱搜,也就是我們無法通過默認(rèn)的配置實(shí)現(xiàn)掃描@ConfigurationProperties
注解的類迟郎,也無法將application.yml/application.properties
文件的配置內(nèi)容與實(shí)體類內(nèi)的屬性進(jìn)行綁定。
解決問題
SpringBoot
官方給出的解決方法是手動(dòng)在@SpringBootApplication
注解的類上手動(dòng)添加@ConfigurationPropertiesScan
即可聪蘸,如下所示:
/**
* 2.2.1.RELEASE版本屬性綁定問題解決
*
* @author 恒宇少年
*/
@SpringBootApplication
@ConfigurationPropertiesScan
public class SpringbootConfigurationBindingBitPittedApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootConfigurationBindingBitPittedApplication.class, args);
}
}
敲黑板宪肖,劃重點(diǎn)
SpringBoot
的每次中大版本升級(jí)往往會(huì)刪除或者新增一些功能,建議大家關(guān)注SpringBoot
的動(dòng)態(tài)健爬,以免出現(xiàn)類似今天這篇文章的問題控乾,根據(jù)官方的文檔及時(shí)做出調(diào)整。
代碼示例
微信掃碼下圖二維碼關(guān)注“程序員恒宇少年”后娜遵,回復(fù)“源碼”即可獲取源碼倉庫地址蜕衡。
本章節(jié)源碼在spring-boot-chapter
倉庫內(nèi)目錄為springboot2-2-configuration-binding-bit-pitted