应用中有多个Spring Property PlaceHolder导致@Value只能获取到默认值

背景

工作中负责的一套计费系统需要开发一个新通知功能,在扣费等事件触发后发送MQ,然后消费MQ发送邮件或短信通知给客户。因为有多套环境,测试时需要知道是从哪套环境发出的邮件,又不想维护多套通知模板,因此就打算在各环境的properties中声明不同的title前缀,实现类似[DEV]您的xx月账单[TEST]您的xx月账单的效果,但是这个前缀需要在生产环境中去掉,因此我想到用Spring @Value的默认值来实现,伪代码如下:


@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一直只能获取到默认值。

工程采用spring标签声明了两个property-placeholder,分别读取不同的配置文件:

<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属性值注入出现的问题,google一番后,找到一篇相同问题的文章spring-boot-spring-always-assigns-default-value-to-property-despite-of-it-bein

按照 SPR-9989 上的说明,Spring在有多个property-placeholder时,如果第一个property-placeholder在处理@Value时没有找到属性值,则会采用默认值对属性进行赋值,然后第二个property-placeholder就会忽略该@Value,于是@Value获取到的永远都是默认值。

问题解决

合并property-placeholder声明:

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

追加

这个bug一直是未修复状态,好像Spring官方不认为这是一个bug?截至spring 5.2.x版本也有这个问题。

转载于:https://www.cnblogs.com/larva-zhh/p/11395844.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值