Friday, May 02, 2008

PropertyPlaceholderConfigurer doesn't work with XmlBeanFactory

SImple gotcha.

I was using Spring and the PropertyPlaceholderConfigurer. This simply allows you to populate your spring config file with values from a properties file at runtime. For me the properties file is loaded from the classpath (using the classpath: prefix). this is then stored in a seperate config folder whihc is shared between all projects, thus allowing us to update the config file with needing to redploy the complete application again.

e.g.

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jms.properties</value>
<ref bean="getNetworkServicePropertyFile" />
</list>
</property>
</bean>
<bean id="test" class="com.meteor.provisioning.Test">
<property name="jmsTemplate" value="${jms.receiveTimeout}" />
</bean>


I write a simple class to instantiate this from a Unit test.


public static BeanFactory getSpringContext() {
springConfigFile = System.getProperty("SpringConfig", springConfigFile);
if (_beanFactory == null) {
Resource resource = new ClassPathResource(springConfigFile);
//_beanFactory = new XmlBeanFactory(resource);
}
return _beanFactory;
}
public static Object getBean(String bean){
return getApplicationContext().getBean(bean);
}

and finally a test case

public class Test {
private String jmsTemplate;

public void setJmsTemplate(String jmsTemplate) {
this.jmsTemplate = jmsTemplate;
System.out.println("jmsTemplate = "+jmsTemplate);
}

@org.junit.Test
public void doTest(){
Utils.getBean("test");
}

}



It didn't work. The PropertyPlaceholderConfigurer, wasn't updating the internal spring file with values from the jms.properties. The jmsTemplate value was been returned as ${jms.receiveTimeout}

Turns out that only ApplicationContext files do the replacement. A quick update to

public static ApplicationContext getApplicationContext() {
springConfigFile = System.getProperty("SpringConfig", springConfigFile);
if (_beanFactory == null) {
_beanFactory = new ClassPathXmlApplicationContext(springConfigFile);
}
return _beanFactory;
}

fixed the problem. Thanks also to http://francisoud.blogspot.com/2007/06/spring-property-placeholder.html

No comments: