首先在spring的配置文件任意地方配置一个bean
xml 代码
?
- <bean?id="propertyConfigurer"?class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">??
- ????????<property?name="location"?value="/WEB-INF/classes/jdbc.properties"?/>??
- ????</bean>??
然后生成一个 jdbc.properties 文件 放到相应的路径
jdbc.properties
java 代码
?
-
jdbc.username?=?sa??
-
jdbc.password?=?1234??
-
jdbc.url?=?jdbc:jtds:sqlserver:??
-
jdbc.driverClassName?=?net.sourceforge.jtds.jdbc.Driver??
现在就可以在spring配置文件中使用这些属性了
例如
xml 代码
?
-
<bean?id="dataSource"?class="org.apache.commons.dbcp.BasicDataSource">??
-
????????<property?name="username"?value="${jdbc.username}"/>??
-
????????<property?name="password"?value="${jdbc.password}"/>??
-
????????<property?name="url"?value="${jdbc.url}"/>??
-
????????<property?name="driverClassName"?value="${jdbc.driverClassName}"/>??
-
????</bean>??
?
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////?
1.system.properties
database.url=jdbc:mysql://localhost/smaple database.driver=com.mysql.jdbc.Driver database.user=root database.password=root
2.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>>classpath:system.properties</value> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="url"> <value>${database.url}</value> </property> <property name="driverClassName"> <value>${database.driver}</value> </property> <property name="username"> <value>${database.user}</value> </property> <property name="password"> <value>${database.password}</value> </property>
</bean> </beans>
当放入多个配置文件时 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>>classpath:system1.properties</value> <value>>classpath:system2.properties</value> </list> </property> </bean>
还可以这样 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:*.properties</value> </list> </property> </bean>
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|