Friday, June 15, 2012

Spring PropertySourcesPlaceholderConfigurer - overriding properties for tests

PropertySourcesPlaceholderConfigurer provides a good way to load in configuration from property files and populate the Spring bean definition property values. It is configured using a custom tag provided by Spring:

<context:property-placeholder location="classpath*:META-INF/spring/"/>

Say, for eg, if I had peristenceUnitName as a property loaded in from, I could use this property to configure my EntityManagerFactory:

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
    <property name="dataSource" ref="dataSource"/>
    <property name="persistenceUnitName" value="${persistenceUnitName}"></property>

So, now I want to override the name of the persistence unit for running my tests. A reasonable solution would be to define another PropertySourcesPlaceholderConfigurer in the test context with a different value of the "persistenceUnitName", this will work if the test placeholder is loaded up BEFORE the main application context.

A better way to go about doing this is using a local-override flag of property-placeholder tag, what this indicates is that the local properties should have a higher precedence over the one's loaded from the file -

<context:property-placeholder location="classpath*:META-INF/spring/" local-override="true" properties-ref="localProperties"/>

<util:properties id="localProperties">

I have provided a dummy localProperties above, just as a place holder.

So now, to override the desired properties in test, the only thing that needs to be done is to define a new localProperties bean this way:
<util:properties id="localProperties">
     <prop key="persistenceUnitName">TEST-tasksPersitenceUnit</prop>

This I feel is a much cleaner approach to defining placeholder properties that are to be overridden in the tests.

No comments:

Post a Comment