應用中有多個Spring Property PlaceHolder致使@Value只能獲取到默認值

背景

工做中負責的一套計費系統須要開發一個新通知功能,在扣費等事件觸發後發送MQ,而後消費MQ發送郵件或短信通知給客戶。由於有多套環境,測試時須要知道是從哪套環境發出的郵件,又不想維護多套通知模板,所以就打算在各環境的properties中聲明不一樣的title前綴,實現相似[DEV]您的xx月帳單[TEST]您的xx月帳單的效果,可是這個前綴須要在生產環境中去掉,所以我想到用Spring @Value的默認值來實現,僞代碼以下:java

@Value("${notice.mail.titlePrefix:}")
private String mailTitlePrefix;

public void doSendEmail() {
    ...
    String title = "xxx";
    if (StringUtils.isNotBlank(mailTitlePrefix)) {
        title = mailTitlePrefix + title;
    }
    mailSender.send(title, content, recevier);
}

採用上述代碼後,運行發現,即便在properties中配置了值,可是mailTitlePrefix一直是空字符串"",一旦把冒號去掉又能正常讀取到配置的值,修改:後面的數據爲其餘值,如@Value("${notice.mail.titlePrefix:113}")mailTitlePrefix的值也爲113,即@Value一直只能獲取到默認值。git

工程採用spring標籤聲明瞭兩個property-placeholder,分別讀取不一樣的配置文件:github

<context:property-placeholder order="0" location="classpath*:db.properties" ignore-unresolvable="true"/>
<context:property-placeholder order="0" location="classpath*:config.properties" ignore-unresolvable="true"/>

notice.mail.titlePrefix的配置在config.properties文件中。spring

問題定位

能夠肯定是spring屬性值注入出現的問題,google一番後,找到一篇相同問題的文章spring-boot-spring-always-assigns-default-value-to-property-despite-of-it-beinspring-boot

按照 SPR-9989 上的說明,Spring在有多個property-placeholder時,若是第一個property-placeholder在處理@Value時沒有找到屬性值,則會採用默認值對屬性進行賦值,而後第二個property-placeholder就會忽略該@Value,因而@Value獲取到的永遠都是默認值。測試

問題解決

合併property-placeholder聲明:google

<context:property-placeholder order="0" location="classpath*:db.properties,classpath*:config.properties" ignore-unresolvable="true"/>

追加

這個bug一直是未修復狀態,好像Spring官方不認爲這是一個bug?截至spring 5.2.x版本也有這個問題。完整的TestCase詳見larva-zhang/some-problems-record/spring-always-assigns-default-value-to-Value-annotationspa

相關文章
相關標籤/搜索