Conditional Statement in Spring Config

Sometimes we may need to have some conditional statement in Spring config XML file depending upon some variables value.

Think of a situation when you are using JPA in your application and your application may have two persistence units in Spring XML config file and you need to connect to one of them depending upon the environments. Here conditional statement in Spring config comes to rescue. For example, when you write code in your local system and want to test the application then you do not want to connect to the live database but you want to connect to in-memory database such as H2 or Derby or any other in-memory database due to having some constraints connecting from local system and when you deploy your code into other environments such as Dev, SIT, UAT, PROD then during this time only you want to connect to the live database. So in such situtation you may have two persistence units one for local and another for all other environments with the same schema. Therefore you want to pass a VM argument that will take your environment value and will connect to the appropriate persistence unit.

Example

In this example we will create two persistence units as shown below.

Persistence Units : 1. OrderManagementLocal 2. OrderManagementLive

VM argument : environment

Now suppose you have two persistence units in persistence.xml file something similar to below configuration.

<persistence-unit name="OrderManagementLocal">
    <provider>...</provider>
 etc.
    <properties>
        <property name="..." value="..."/>
    </properties>
</persistence-unit>
<persistence-unit name="OrderManagementLive">
    <provider>...</provider>
 etc.
    <properties>
        <property name="..." value="..."/>
    </properties>
</persistence-unit>

And if your application is having below entityManagerFactory then depending upon the VM argument’s value you can switch between persistence units using Spring EL expression as shown below in XML config. So if your VM argument’s value is local then you select OrderManagementLocal otherwise you choose OrderManagementLive persistence unit.

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <property name="persistenceXmlLocation" value="classpath:persistence.xml" />
 <property name="persistenceUnitName" value="#{systemProperties.environment=='local'?'OrderManagementLocal':'OrderManagementLive'}" />
</bean>

The VM argument is configured to the Tomcat server’s VM arguments section as shown below

-Denvironment=local

Now you have got idea how to use conditional statement in Spring config and hope you will be able to use the same concept to your own project.

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *