在配置文件里配置 Bean 时, 有时需要在 Bean 的配置里混入系统部署的细节信息(例如: 文件路径, 数据源配置信息等). 而这些部署细节实际上需要和 Bean 配置相分离
Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器, 这个处理器允许用户将 Bean 配置的部分内容外移到属性文件中. 可以在 Bean 配置文件里使用形式为 $ {var } 的变量, PropertyPlaceholderConfigurer 从属性文件里加载属性, 并使用这些属性来替换变量.
Spring 还允许在属性文件中使用 ${ propName},以实现属性之间的相互引用。
我们以配置C3p0的数据源为例
下载c3p0的jar包,点击下载
下载mysql的jdbc包,点击下载
将c3p0的jar包和mysql的jdbc jar包放入项目工程中
新建一个beans-properties.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1/Test"></property>
</bean>
</beans>
调用该bean
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
输出结果如下
com.mchange.v2.c3p0.impl.NewProxyConnection@fcd6521 [wrapping: com.mysql.jdbc.JDBC4Connection@27d415d9]
说明c3p0搭建完成
然而,在一般的项目中,bean文件中会有非常多的bean,一旦需要修改,很有可能会造成错误。
因此,对于这种情况我们一般讲这些配置内容提取出来到一个propertis文件中
新建一个db.properties文件
user=root
password=123456
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://127.0.0.1/Test
那如何引用这个文件呢?Spring为我们提供了PropertyPlaceholderConfigurer,可以通过它来完成这个操作
在spring2.0 之前,我们需要进行如下配置
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"></property>
</bean>
而在Spring2.5之后,我们只需要作如下配置
<!-- 导入属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
完成上述PropertyPlaceholderConfigurer 的配置后,我们只需要使用${ column}就可以调用property文件中的值
XML配置
<!-- 导入属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
</bean>
注意,${user} 需要加上双引号,否则会报错
调用bean
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-properties.xml");
DataSource dataSource = (DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
输出结果
com.mchange.v2.c3p0.impl.NewProxyConnection@6d3af739 [wrapping: com.mysql.jdbc.JDBC4Connection@1da51a35]
建议使用如上的方法来配置数据源之类的bean