July 16, 2011

Externalizing literal values from the applicationContext.xml into a properties file

0) Refer to the example for wiring collections into a spring bean here

1) Add the following configuration in the applicationContext.xml to enable externalizing literal values into a properties file

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location"   
       value="classpath:resources/MessageResources.properties" />
</bean>

2) Add a new properties file - MessageResources.properties in the resources package (within the src folder). Add the following contents in the MessageResources.properties

list.string1=String 1 externalized
list.string2=String 2 externalized
list.string3=String 3 externalized

3) Modify the configuration for the bean in the wiring collections example, in the applicationContext.xml, as follows,

<bean id="listExample"
         class="info.icontraining.spring.CollectionsExample">
   <property name="myList">
      <list>
         <value>${list.string1}</value>
         <value>${list.string2}</value>
         <value>${list.string3}</value>
      </list>
   </property>
   <property name="myMap">
      <map>
         <entry key="key1" value="value1" />
         <entry key="key2" value="value2" />
         <entry key="key3" value="value3" />
      </map>
   </property>
</bean>

4) Test the code with the following URL in the browser,

http://localhost:8080/TestWebApp/springTest.jsp

No comments:

Post a Comment