应用中有多个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

相关文章
相关标签/搜索