一、建立com.util下建立db.properties文件
name=root driver=com.mysql.jdbc.Driver url=jdbc\:mysql\://localhost\:3306/bookmanage pwd=123456
建立DBUtil.java
public class DBUtil { private String name; private String driver; private String url; private String pwd;
配置xml(配置方式1)
<!-- 引入properties文件 --> <context:property-placeholder location="classpath:com/util/db.properties"/> <!-- 使用占位符$表示properties文件中的變量 --> <bean id="dbutil" class="com.util.DBUtil"> <property name="name" value="${name}"></property> <property name="url" value="${url}"></property> <property name="driver" value="${driver}"></property> <property name="pwd" value="${pwd}"></property> </bean>
配置xml(配置方式2)
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>com/util/db.properties</value> </list> </property> </bean> <!-- 使用占位符$表示properties文件中的變量 --> <bean id="dbutil" class="com.util.DBUtil"> <property name="name" value="${name}"></property> <property name="url" value="${url}"></property> <property name="driver" value="${driver}"></property> <property name="pwd" value="${pwd}"></property> </bean>
二、如果要引入多個properties文件怎么引入
注意:引入的多個properties文件中有多個名字相同的屬性,則使用后引入的文件中的值
雖然不報錯,但是我們如果要為了避免混淆,會給屬性名前面加上文件名
db.name=root db.driver=com.mysql.jdbc.Driver db.url=jdbc\:mysql\://localhost\:3306/bookmanage db.pwd=123456
那引用的時候就引用${db.xxx}了
配置多個properties文件
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>com/util/db.properties</value> <value>com/util/db2.properties</value> </list> </property> </bean>
<context:property-placeholder location="classpath:com/util/db.properties,classpath:com/util/db2.properties"/>
三、BUG
有時候配置的沒問題,但是卻有bug
Error creating bean with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0': Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions
網上查了資料是,spring的命名空間有問題,我們需要在xml中統一spring的版本為3.0
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd ">