我尝试实现一个自己的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
但${password}
的构造函数中的属性MyPropertyPlaceholderConfigurer
未解析。
我的错误是什么?
答案 0 :(得分:0)
我发布了解决这个问题的解决方案。
我实现了一个PropertyPlaceholderConfigurer,它可以加载所有属性并为某些属性添加特殊功能。这样,在PropertyPlaceholderConfigurer中,您就可以使用已加载属性文件中定义的属性。
config.properties
password=1234
special.properties
user={SPECIAL}name
spring config:
<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;
}
}
也许对某人有帮助。