spring - 覆盖 PropertyPlaceholderConfigurer 中的属性值

标签 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} 中注入(inject) base.url 值。

我应该如何在运行时更新给定属性的值。上面的代码总是采用属性文件中的值而不是更新后的值。

最佳答案

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

Note: Properties defined in later files will override properties defined earlier files, in case of overlapping keys. Hence, make sure that the most specific files are the last ones in the given list of locations.

从 Spring 5.2 开始,这已被弃用,取而代之的是 PropertySourcesPlaceholderConfigurer:

Specialization of PlaceholderConfigurerSupport that resolves ${...} placeholders within bean definition property values and @Value annotations against the current Spring Environment and its set of PropertySources.

一些例子here

关于spring - 覆盖 PropertyPlaceholderConfigurer 中的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834526/

相关文章:

java - 显示从 json 响应中检索到的所有内容

spring - 使用 Spring 直接连接一个具体的类

java - 如何通过 gradle 任务使用 spring 配置文件运行 bootRun

java - Spring中使用表达式语言出错

java - 为什么 RestTemplate 会消耗过多的内存?

java - 有异常(exception)。 Spring 3 与 Spring Tool Suite、Tomcat 7 和 Maven

java - Spring 2.5.1 是否与 JDK 1.7 兼容

java - 在已经使用 spring-mvc 作为依赖项的依赖项的应用程序中设置 spring-mvc

java - Spring JdbcTemplate.update() 没有更新行