Spring Configuration file
Updated: 2009-03-07
Problem
Spring is managing the database connection of my application. I want to extract the parameters outside my applicationContext.xml
file:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/database" />
<property name="username" value="user"/>
<property name="password" value="password"/>
</bean>
Solution
Add the PropertyPlaceholderConfigurer bean to your ApplicationContext with the name of the file(s) containing the data.
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>WEB-INF/data.properties</value>
</property>
</bean>
If you have more property files you can use the tag:
<property name="locations">
<list>
<value>data.properties</value>
<value>other-file.properties</value>
</list>
</property>
The data.properties
should be like this:
database.url=jdbc:mysql://localhost/database
database.username=username
database.password=password
To use these properties in your applicationContext.xml
file:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</bean>