Reputation: 5093
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.
Upvotes: 9
Views: 23668
Reputation: 1
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
Upvotes: 0
Reputation: 3344
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.
Upvotes: 16
Reputation: 17734
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.
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."
Upvotes: 1
Reputation: 29139
Spring has builtin support for specifying properties within the application context XML. See section 3.3.2.4 of the Spring Reference docs.
Upvotes: 1