Thursday, October 18, 2012

A solution to have environment specific Spring application context files

I found this post today : http://www.drillio.com/en/software-development/spring/context-bootstrapping-with-different-environment-configurations/
 
I have the following problem : I need to customize a web application. For example, on a production environment, I want my app to be automatically configured with production parameters. As this application uses Spring namespaces (grrrr), I can't use a DefaultPropertyPlaceHolderConfigurer to inject properties dynamically into config files. I really need to have Spring conf files per environment.

I made some changes to the code to make it compatible with Spring 2.5.6. Here are my classes :


https://sites.google.com/site/javacolorsfiles/SpringContextBootstrapper.java
https://sites.google.com/site/javacolorsfiles/ConfigLocationProviderImpl.java
https://sites.google.com/site/javacolorsfiles/ConfigLocationProvider.java

And an example of Spring conf behind :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
                http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <bean name="bootstrap" class="com.essec.spring.extension.bootstrapper.SpringContextBootstrapper" init-method="init">
        <property name="configLocations">
            <list>
                <value>classpath:applicationContext.xml</value>
            </list>
        </property>
    </bean>

    <!-- and this is a modified content from one of our live applications -->
    <bean class="com.essec.spring.extension.bootstrapper.ConfigLocationProviderImpl">
        <property name="configLocations">
            <list>
                <!-- here comes our dynamic config location -->
                <value>classpath:${spring.applicationContext}</value>
            </list>
        </property>
    </bean>

</beans>