Search

Dark theme | Light theme

March 8, 2009

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

In the previous parts (part 1, part 2, part 3, part 4, part 5) we learned a lot about the Spring Configurator. But the documentation of the Spring Configurator is a bit sparse (if we can find it on the website, which is a task in itself).

So browsing the mailing lists and source code I found a hidden feature. We can define default values for a property in the property references. If the value for the property cannot be found the default value is used. The following Spring configuration contains this default value for the property sample.text1. This property is not defined anywhere so the default value after the colon is used (see line 15):

<?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:context="http://www.springframework.org/schema/context"
       xmlns:configurator="http://cocoon.apache.org/schema/configurator"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://cocoon.apache.org/schema/configurator http://cocoon.apache.org/schema/configurator/cocoon-configurator-1.0.1.xsd">

    <context:component-scan base-package="com.mrhaki.netbeans.mavenapp"/>
    <configurator:settings/>

    <bean name="sample" class="com.mrhaki.netbeans.mavenapp.Sample">
        <property name="text" value="${sample.text1:Default value}"/>
    </bean>

</beans>

If we run our test (mvn test) with the test class from part 1, we get as output:

Running in [prod] mode. Text = [Default value] and timeout = [1000].

We see how the property text now contains the default value we specified in the property reference in the Spring configuration file.