是否有可能通过 Apache Commons 配置将 Spring PropertyPlaceholderConfigurer 配置为从 properties.xml 中读取?
问问题
7090 次
3 回答
3
我在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。
随意复制和粘贴!
于 2010-07-06T08:26:29.483 回答
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>
于 2010-07-02T07:42:16.233 回答
1
这是使用弹簧模块的解决方案。我不知道这是多么最新,但即使不是,您也可以轻松获取代码并使其适用于当前版本。
于 2010-07-02T12:26:06.817 回答