Tutorial :Store Custom properties in aplicationContext.xml Spring file



Question:

I need to store some configuration parameters for a web application that uses spring framework.

Typically I'll use a configurationfile.properties file but i wonder if i can store that values in the applicationContext.xml file.

One workaround could be to create a JavaBean class to store the values, and build that class using spring, something like this:

<bean id="configurationBean" class="mypackage.someClass">   <property name="confValue1">     <value>myValue1</value>   </property>   ....  </bean>  

But i would like to know if is there a way to store those parameters without the needing to create that class.

Thanks in advance.


I think that the best solution that fits my requirements is to use a java.util.Properties instance as a Spring Bean.

Thank you all.


Solution:1

This should work with the following syntax.

<bean id="props" class="java.util.Properties" >      <constructor-arg>          <props>              <prop key="myKey">myValue</prop>              <prop ...>          </props>      </constructor-arg>  </bean>  

You are taking advantage of the fact that java.util.Properties has a copy constructor that takes a Properties object.

I do this for a HashSet which also has a copy constructor (as do HashMaps and ArrayLists) and it works perfectly.


Solution:2

Spring has builtin support for specifying properties within the application context XML. See section 3.3.2.4 of the Spring Reference docs.


Solution:3

I think you'll get the best results using Spring's PropertyPlaceholderConfigurer which allows you to map values from a regular .properties file against properties defined on your beans.

http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer

The example shows how to set the JDBC connection properties directly on an instance of javax.sql.DataSource, eliminating the need for an intermediate "configuration bean."


Solution:4

The best way is to use spring PropertyPlaceholderConfigurer

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">      <property name="locations">          <list>              <value>classpath:yourconfigurationfile.properties</value>          </list>      </property>  </bean>  

then

<bean id="configurationBean" class="mypackage.someClass">      <property name="confValue1">          <value>${myvalue1}</value>      </property>      ....  </bean>    

and in yourconfigurationfile.properties

myvalue1= value1  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »