是否可以配置Spring PropertyPlaceholderConfigurer进行读取 properties.xml,通过Apache Commons配置?
答案 0 :(得分:3)
<!-- 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 Testclass
@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。
随意复制&amp;粘贴!
答案 1 :(得分:2)
最简单的方法(也许不是最好的方法)是继承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>
答案 2 :(得分:1)
这是solution using spring modules。我不知道目前的情况如何,但即使不是,你也可以轻松地获取代码并使其适用于当前版本。