Spring – Configuration file
source link: https://marco.dev/2009/03/07/spring-configuration-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
java-version.com: What's new in Java 16? 15? Keep up to date!
Spring – Configuration file
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>...</value> </list> </property>
The data.properties should be like this:
database.url= jdbc:mysql://localhost/CheckNames 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}</value></property> <property name="username"><value>${database.username}</value></property> <property name="password"> <value>${database.password}</value></property> </bean>
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK