有没有可能配置Spring PropertyPlaceholderConfigurer从properties.xml中读取,通过Apache Commons Configuration?
在 seanizer 和 springmodule 的帮助下,我找到了解决方案。
<!-- Composite configuration -->
<bean id="configuration" class="org.springmodules.commons.configuration.CommonsConfigurationFactoryBean">
<property name="configurations">
<list>
<!-- User specifics -->
<bean class="org.apache.commons.configuration.XMLConfiguration">
<constructor-arg type="java.net.URL" value="file:cfg.xml" />
</bean>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="configuration"/>
</bean>
<bean id="testConfig" class="uvst.cfg.TestConfiguration">
<property name="domain" value="${some.prop}"></property>
</bean>
TestConfiguration类
public class TestConfiguration {
private String domain;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
}
jUnit测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( { "/applicationContextTest.xml" })
public class ApacheCommonCfg2Spring extends AbstractJUnit4SpringContextTests {
private TestConfiguration tcfg;
@Test
public void configuration(){
tcfg = this.applicationContext.getBean("testConfig", TestConfiguration.class);
System.out.println(tcfg.getDomain());
}
}
Springmodule相当古老,似乎已经不再维护,但它可以与Spring 3.0.3一起使用。
请随意复制并粘贴!
最简单的方法(虽然可能不是最好的)是继承PropertyPlaceholderConfigurer类,加载commons配置文件,并将其传递给超类:
public class TestPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
public TestPlaceholderConfigurer()
{
super();
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException
{
XMLConfiguration config = new XMLConfiguration("config.xml");
Properties commonsProperties = config.getProperties("someKey")
// Or something else with the configuration
super.processProperties(beanFactoryToProcess, commonsProperties);
}
}
然后您只需将该类用作placeholderConfig:
<bean id="placeholderConfig"
class="com.exampl.TestPlaceholderConfigurer ">
<!-- ... -->
</bean>