PropertyPlaceholderConfigurer reads an XML file (Apache Commons configuration)

Is it possible to configure the Spring PropertyPlaceholderConfigurer to read from properties.xml through the Apache Commons configuration?

+4
source share
3 answers

I found a solution using seanizer and 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> 

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 is quite old, it seems that it is no longer supported, but works with Spring 3.0.3.

Feel free to copy and paste!

+3
source

The easiest way (maybe not the most enjoyable) is to subclass PropertyPlaceholdConfigurer, load the community configuration, and then pass it to the superclass:

 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); } } 

Then you just use this class as placeholderConfig:

 <bean id="placeholderConfig" class="com.exampl.TestPlaceholderConfigurer "> <!-- ... --> </bean> 
+2
source

Below is a solution using spring modules . I don’t know how relevant this is, but even if it’s not, you can probably easily take the code and make it work with current versions.

+1
source

Source: https://habr.com/ru/post/1314516/


All Articles