Loading...

March 5, 2009

Use Spring Configurator to support different dev, test and production environments with Spring configuration files (Part 4)

The Spring configurator has even more to offer than the things we have learned in the previous parts (part 1, part 2, part 3). If we place Spring configuration files at certain locations in our application classpath then they will be added to the existing Spring application context. This means we don't have to explicitly add the configuration files another configuration with an import, it is available automatically. And as we can guess we can use this even per running mode.

In the documentation we can see where we must place the Spring configuration files. For our example we create a new Spring configuration file in the src/main/resources/META-INF/cocoon/spring directory and name it anotherContext.xml. Here is the contents of the file:

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

    <bean name="anotherSample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="I am the other sample from anotherContext.xml."/>
    </bean>
</beans>

We define another bean for the same sample class and give the property text a new value (see line 8).

In our test class we add a statement to print out the value for this property (see line 21). So we get the following test:

package com.mrhaki.spring.mavenapp;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class AppTest extends TestCase {

    public AppTest(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(AppTest.class);
    }

    public void testApp() {
        final ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(appContext.getBean("sample"));
  System.out.println(appContext.getBean("anotherSample"));
    }
}

When we run the test (mvn test) we get the following output:

Running in [prod] mode. Text = [We are alive!] and timeout = [1000].
Running in [prod] mode. Text = [I am the other sample from anotherContext.xml.] and timeout = [1000].

So we see we didn't define anywhere to load anotherContext.xml, but we can use all beans defined in it! The Spring configuration file is loaded by the Spring configurator, because of the placement of the file in the classpath.