工做中負責的一套計費系統須要開發一個新通知功能,在扣費等事件觸發後發送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-bein。spring-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