在PropertyPlaceholderConfigurer中覆盖属性值

时间:2015-08-05 13:52:27

标签: spring spring-2.5

我需要在加载JBOSS应用程序服务器时覆盖我的属性文件中给出的属性值。

我尝试使用以下代码覆盖PropertyPlaceholderConfigurer中的processProperties()方法。

我的属性文件有此条目

base.url =" defaultUrl"

public class CustomPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

protected String convertPropertyValue(String originalValue) {
    return (originalValue != null) ? originalValue.trim() : originalValue;
}

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props)
        throws BeansException {
    super.processProperties(beanFactory, props);
    for (Enumeration names = props.propertyNames(); names.hasMoreElements();) {
        String key = (String) names.nextElement();
        props.put("base.url", getUpdatedUrl());
    }
}

}

我在应用程序上下文中的占位符$ {base.url}中注入了base.url值。

如何在运行时更新给定属性的值。上面的代码始终采用属性文件中的值而不是更新的值。

1 个答案:

答案 0 :(得分:0)

从这个问题吹走灰尘。可以使用PropertyPlaceholderConfigurer并添加一个新的属性文件(在列表的末尾)来完成此操作,在该文件中放置要覆盖的属性。 (属性文件的名称/文件路径可以包含您在构建时传递的环境变量)。这是PropertiesLoaderSupport#setLocations的Javadoc:

  

注意:在以后的文件中定义的属性将覆盖属性   如果键重叠,则定义较早的文件。因此,请确保   最具体的文件是给定列表中的最后一个   位置。

从Spring 5.2开始,不推荐使用此方法,而推荐使用PropertySourcesPlaceholderConfigurer:

  

可解析$ {...}的PlaceholderConfigurerSupport专业化   bean定义属性值和@Value中的占位符   针对当前Spring Environment及其集合的注释   PropertySources。

一些示例here