【问题标题】:Use properties of other property placeholder in own property placeholder configurer在自己的属性占位符配置器中使用其他属性占位符的属性
【发布时间】:2015-07-03 06:43:07
【问题描述】:

我尝试实现一个自己的PropertyPlaceholderConfigurer,它在构造函数中使用另一个PropertyPlaceholderConfigurer 的属性。我试着这样做。

<!-- load properties which are used in second configurer -->
<context:property-placeholder 
        location="classpath:config.properties" ignore-unresolvable="true" order="1" /> 

<bean class="com.example.MyPropertyPlaceholderConfigurer">
        <!-- use property of other file -->
        <constructor-arg value="${password}" />
        <property name="location">
            <value>file:config.properties</value>
        </property>
        <property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>

config.properties

password=1234

但是MyPropertyPlaceholderConfigurer的构造函数中的属性${password}没有解析。

我的错误是什么?

【问题讨论】:

  • 我不知道为什么有些火鸡把你记下来了:(。问:你提到“conf.properties”;你的代码有“config.properties”和“config2.properties”。有吗真的是三个不同的文件?还是拼写错误?
  • 我的错误。我在问题中拼错了。但是文件在那里。我在其他位置使用第一个占位符的属性,它们在那里得到解决。
  • 那行不通(正如您已经经历过的那样)。使用属性占位符不是一个多步骤过程,它们都是BeanFactoryPostProcessors 并且在生命周期的早期运行,它们不会相互操作。唯一可行的占位符替换是基于系统属性。
  • 好的。非常感谢您的澄清。 PropertyOverrideConfigurer 也是这种情况吗? (我也尝试过这种方法,但没有运气)

标签: java spring


【解决方案1】:

我特此发布我想出的解决这个问题的解决方案。

我实现了一个 PropertyPlaceholderConfigurer,它加载所有属性并向某些属性添加特殊功能。通过这种方式,您可以在 PropertyPlaceholderConfigurer 中使用在加载的属性文件中定义的属性。

config.properties

password=1234

special.properties

user={SPECIAL}name

弹簧配置:

<bean
    class="com.example.MyPropertyPlaceholderConfigurer">
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="locations">
        <list>
            <value>classpath:config.properties</value>
            <value>classpath:special.properties</value>
        </list>
    </property>
</bean>

PropertyPlaceholderConfigurer:

public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private final static String PROPERTY_PREFIX = "{SPECIAL}";

    protected Properties properties;

    @Override
    protected void convertProperties(Properties props) {
        this.properties = props;
        super.convertProperties(props);
    }

    @Override
    public String convertPropertyValue(String originalValue) {
        if (originalValue.startsWith(PROPERTY_PREFIX)) {
            return convert(originalValue.substring(PROPERTY_PREFIX.length()));
        }
        return originalValue;
    }

    protected String convert(String value){
        // access properties from config.properties
        String pw = this.properties.getProperty("password");
        // use properties and do what you need to do
        return value + pw;
    }

}

也许它对某人有帮助。

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2014-07-16
    相关资源
    最近更新 更多