【发布时间】:2011-03-10 23:33:02
【问题描述】:
是否有可能配置 Spring PropertyPlaceholderConfigurer 以读取 properties.xml,通过 Apache Commons 配置?
【问题讨论】:
标签: java spring properties apache-commons
是否有可能配置 Spring PropertyPlaceholderConfigurer 以读取 properties.xml,通过 Apache Commons 配置?
【问题讨论】:
标签: java spring properties apache-commons
我在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>
类测试配置
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。
随意复制和粘贴!
【讨论】:
这是solution using spring modules。我不知道这是多么最新,但即使不是,您也可以轻松获取代码并使其适用于当前版本。
【讨论】:
最简单的方法(虽然可能不是最好的)是继承 PropertyPlaceholdeConfigurer,在那里加载公共配置,然后将其传递给超类:
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>
【讨论】: