March 1, 2009

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

Okay we have learned about the running modes in part 1 and we saw how to use the property configurer in part 2. In this part we see how we can use the property overrider.

Suppose we have a Java class configured in the Spring context with a default value and want to override this value for a specific running mode. That is where the property overrider comes into play.

We add a new timeout property to our Sample class:

package com.mrhaki.spring.mavenapp;

import org.apache.cocoon.configuration.Settings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

public class Sample {

    private Settings settings;

    private String text;
    private int timeout = 1000;

    public void setSettings(Settings settings) {
        this.settings = settings;

    public void setText(String name) {
        this.text = name;
    public void setTimeout(int timout) {
        this.timeout = timeout;

    public String toString() {
        return "Running in [" + settings.getRunningMode() + "] mode. "
                + "Text = [" + text + "] and timeout = [" + timeout + "].";

If we read the documentation we see we must define a property file and can place it in different locations. For our example we create a property file at src/main/resources/META-INF/cocoon/spring/dev/timeout.properties. And we use the following content:


This property file will be used in the dev running mode by the Spring Configurator. The property file will override bean configurations set in the Spring context. The Spring Configurator uses the / to separate the bean name and property. In our example we override the timeout property of the sample bean.

When we run the test in dev running mode, mvn test -Porg.apache.cocoon.mode=dev, we get the following output:

Running in [dev] mode. Text = [We are developing!] and timeout = [42].

And if we run the example in prod mode, mvn test, we get the following output:

Running in [prod] mode. Text = [We are alive!] and timeout = [1000].

This way we can easily override properties already set by code in Spring configurations! In the next part we see how the Spring Configurator can load Spring configuration files automatically.