合理地使用这个类,可以在开发过程中,对原来完全由spring配置的一些东西,如数据库连接池,进行动态配置。
具体用法:
首先,在web.xml里面配置spring的启动的监听器,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
并且配置spring配置文件的位置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/spring-*.xml</param-value>
</context-param>
然后,我们在spring-ds.xml中来配置数据库连接池的一些信息。
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${DBDriverClassName}" />
<property name="jdbcUrl" value="${DBJDBCUrl}" />
<property name="user" value="${DBUserName}" />
<property name="password" value="${DBPassword}" />
........................
</bean>
上面只配置了部分数据库连接池的属性。可以看到,对于数据库连接的驱动,url,用户名和密码我都是通过$符在内存中动态获取出来的的。
如:${DBDriverClassName}
那么,这些变量我是在哪里设置的呢。如下:
那么最后一步,就是自定义一个类,继承PropertyPlaceholderConfigurer。这样,在spring启动之后,扫描spring-*.xml配置文件之前,就会执行PropertyPlaceholderConfigurer的继承类中的loadProperties(Properties props)方法,将配置信息如:DBDriverClassName注入到Properties 内存中。并在spirng-*.xml中通过$符获取。${DBDriverClassName}
public class PropertyPlaceholderConfigurer extends org.springframework.beans.factory.config.PropertyPlaceholderConfigurer {
@Override
protected void loadProperties(Properties props) throws IOException {
String dBJDBCUrl = "XXX";
...
//props设置将属性设置进去,在spring-*.xml中通过${DBJDBCUrl}获取出来
props.setProperty("DBJDBCUrl", dBJDBCUrl);
props.setProperty("DBUserName", dBUserName);
props.setProperty("DBPassword", dBPassword);
props.setProperty("DBDriverClassName", dBDriverClassName);
super.loadProperties(props);
}
}
如上所示:我们可以将数据库驱动信息DBDriverClassName,用户名DBUserName密码DBPassword,配置在一个文本文件中,然后在loadProperties()方法里面对他们进行加载,并设置进入Properties ,从而实现根据具体的应用环境,实现数据库的动态切换。