PropertyPlaceholderConfigurer从XML文件读取(Apache Commons配置)

是否有可能通过Apache Commons Configuration将Spring PropertyPlaceholderConfigurer配置为从properties.xml读取?

我在seanizer和springmodule的帮助下找到了解决方案

                 

class 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。

随意复制和粘贴!

最简单的方法(也许不是最好的方法)是inheritancePropertyPlaceholdeConfigurer,在那里加载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:

    

这是一个使用弹簧模块的解决方案 。 我不知道当前有多流,但即使不是,你也可以轻松地获取代码并使其适用于当前版本。