1、使用PropertyPlaceholderConfigurer
在applicationContext.xml 中如下配置 <bean id="propertyConfiger" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="jdbc.properties"></property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
jdbc.properties内容如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8
jdbc.username=spring
jdbc.password=spring
2、使用PropertyOverrideConfigurer
<bean id="propertyConfiger" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location" value="jdbc.properties"></property>
</bean>
<bean id="jdbc" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
jdbc.properties内容如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8
jdbc.username=spring
jdbc.password=spring
注意:使用PropertyOverrideConfigurer时,使用${jdbc.url}的bean的名字必须是jdbc,否则可能会出错
3、使用context节点来配置
在applicationContext.xml的<beans ...>节点中添加如下两条内容xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
之后,再配置
<context:property-placeholder location="WEB-INF/jdbc.properties,WEB-INF/mail.properties"/>
注意:
三种情况下必须都使用
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
来加载xml,使用XmlBeanFactory加载,则无法使用。
applicationContext.xml 和properties文件可以放在package里面,只需在指定路径时加上包路径即可,比如applicationContext.xml 放在com.test下,ClassPathXmlApplicationContext("com/test/applicationContext.xml")即可。