前言:

本文旨在介绍Spring动态配置数据源的方式,即对一个DataSource的配置诸如jdbcUrl,user,password,driverClass都通过运行时指定,而非由xml静态配置定死。

Spring构造Context的参数一般只包含配置文件路径和类加载器,如果需要达到动态传入配置参数的目的,需要Spring在初始化数据源相关bean的时候能够对原有配置执行修改或替换,为方便处理,本文将定义一个名为DynamicDataSourceConfigHolder的公共类提供配置数据存储。

本文替换数据源为c3p0配置。

BeanPostProcessor简介:

Spring BeanPostProcesssor通常被称为Spring Bean回调处理器,它一般用于在实例化一个bean的前后增加一些附加操作,它会对全局的Spring bean配置生效。

Spring Bean的生命周期处理:

Spring Bean生命周期通常对应两种处理方式,一种是init-method &destroy-method, 另一种是InitializingBean的afterPropertiesSet()方法和DisposeBean的destroy()方法,BeanPostProcessor的出现使得批处理Spring bean定义有了可能。

BeanPostProcessor定义:

 /**
* Factory hook that allows for custom modification of new bean instances,
* e.g. checking for marker interfaces or wrapping them with proxies.
*
* <p>ApplicationContexts can autodetect BeanPostProcessor beans in their
* bean definitions and apply them to any beans subsequently created.
* Plain bean factories allow for programmatic registration of post-processors,
* applying to all beans created through this factory.
*
* <p>Typically, post-processors that populate beans via marker interfaces
* or the like will implement {@link #postProcessBeforeInitialization},
* while post-processors that wrap beans with proxies will normally
* implement {@link #postProcessAfterInitialization}.
*
* @author Juergen Hoeller
* @since 10.10.2003
* @see InstantiationAwareBeanPostProcessor
* @see DestructionAwareBeanPostProcessor
* @see ConfigurableBeanFactory#addBeanPostProcessor
* @see BeanFactoryPostProcessor
*/
public interface BeanPostProcessor { /**
* Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's <code>afterPropertiesSet</code>
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one; if
* <code>null</code>, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; /**
* Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's <code>afterPropertiesSet</code>
* or a custom init-method). The bean will already be populated with property values.
* The returned bean instance may be a wrapper around the original.
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0). The
* post-processor can decide whether to apply to either the FactoryBean or created
* objects or both through corresponding <code>bean instanceof FactoryBean</code> checks.
* <p>This callback will also be invoked after a short-circuiting triggered by a
* {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
* in contrast to all other BeanPostProcessor callbacks.
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one; if
* <code>null</code>, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; }

以上为Spring源代码,我们重点关注它和Spring bean初始化的关系,即postProcessBeforeInitialization将会在Spring 执行bean初始化钩子(init-method或者afterPropertiesSet)之前被调用。

DynamicDataSourceConfigHolder:

 package org.wit.ff;

 import java.util.Map;

 /**
* 动态数据源配置存储.
* @author ff
*
*/
public class DynamicDataSourceConfigHolder { /**
* 定义本地变量,加入存在多个Spring Context连接多个不同的数据源时,可以共用此类。
*/
private static final ThreadLocal<Map<String,String>> dynamicDataSourceConfigHolder = new ThreadLocal<Map<String,String>>(); public static void setDynamicConfig(Map<String,String> dynamicDataSourceConfig) {
dynamicDataSourceConfigHolder.set(dynamicDataSourceConfig);
} public static Map<String,String> getDynamicDataSourceConfig() {
return (dynamicDataSourceConfigHolder.get());
} public static void clear() {
dynamicDataSourceConfigHolder.remove();
} }

数据源配置文件:

 db.driverClass=****
db.jdbcUrl=****
db.user=****
db.password=****

自定义bean回调处理器:

 package org.wit.ff;

 import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils; import com.mchange.v2.c3p0.ComboPooledDataSource; /**
* Bean回调处理器.
* @author ff
*
*/
public class ComboPooledDataSourceBeanPostProcessor implements BeanPostProcessor { private String dataSourceName; @Override
public Object postProcessAfterInitialization(Object bean, String paramString) throws BeansException {
return bean;
} @Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
// 限制数据源名称和类型.
if (bean instanceof ComboPooledDataSource && dataSourceName.equals(beanName)) {
final Map<String,String> methodMatchField = new HashMap<String,String>();
methodMatchField.put("setDriverClass", "db.driverClass");
methodMatchField.put("setJdbcUrl", "db.jdbcUrl");
methodMatchField.put("setUser", "db.user");
methodMatchField.put("setPassword", "db.password");
// 从公共存储区中加载.
final Map<String, String> config = DynamicDataSourceConfigHolder.getDynamicDataSourceConfig();
ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method paramMethod) throws IllegalArgumentException, IllegalAccessException {
if(methodMatchField.containsKey(paramMethod.getName())){
ReflectionUtils.invokeMethod(paramMethod, bean, config.get(methodMatchField.get(paramMethod.getName())));
}
}
});
}
return bean;
} public void setDataSourceName(String dataSourceName) {
this.dataSourceName = dataSourceName;
} }

Spring 配置文件dynamicDatasource/applicationContext.xml:

  <!-- 加载properties配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- 这里支持多种寻址方式:classpath和file -->
<value>classpath:dynamicDatasource/dbconfig.properties</value>
</list>
</property>
</bean>
<!-- 回调处理器.-->
<bean id="dynamicDataSourceBp" class="org.wit.ff.ComboPooledDataSourceBeanPostProcessor" >
<property name="dataSourceName" value="dataSource" />
</bean> <!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${db.driverClass}" />
<property name="jdbcUrl" value="${db.jdbcUrl}" />
<property name="user" value="${db.user}" />
<property name="password" value="${db.password}" />
</bean>

测试示例:

 Map<String,String> dynamicDataSourceConfig = new HashMap<String,String>();
dynamicDataSourceConfig.put("db.driverClass", "com.mysql.jdbc.Driver");
dynamicDataSourceConfig.put("db.jdbcUrl", "jdbc:mysql://127.0.0.1:3306/menlo3?autoReconnect=true&amp;characterEncoding=utf-8");
dynamicDataSourceConfig.put("db.user", "root");
dynamicDataSourceConfig.put("db.password", "root");
DynamicDataSourceConfigHolder.setDynamicConfig(dynamicDataSourceConfig);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"classpath:dynamicDatasource/applicationContext.xml"}); //执行一段操作数据库的逻辑验证即可. assertNotNull(applicationContext);

Spring BeanPostProcessor与动态加载数据源配置的更多相关文章

  1. atitit.动态加载数据库配置in orm hibernate mybatis

    atitit.动态加载数据库配置in orm 1. 动态加载数据库配置的优点::: 1 1.1. 组合多个配置文件... 1 1.2. 连接多个数据库 1 2. 基本的流程:::getCfg内存对象, ...

  2. ReportViewer动态加载数据源

    ReportViewer主要用于打印和导出数据到pdf或excel,接下来将简单做一张Northwind的Products表的统计报表. (最终图) 一.新建一张报表 二.添加数据集 添加xsd文件后 ...

  3. 在VC中动态加载ODBC的方法

    在使用VC.VB.Delphi等高级语言编写数据库应用程序时,往往需要用户自己在控制面板中配置ODBC数据源.对于一般用户而言,配置ODBC数据源可能是一件比较困难的工作.而且,在实际应用中,用户往往 ...

  4. spring动态加载(刷新)配置文件 [复制链接]

    待验证 在程序开发时,通常会经常修改spring的配置文件,不得不重启tomcat来加载spring配,费时费力.如果能在不重启tomcat的情况下,手动动态加载spring 配置文件,动态重启读取s ...

  5. Spring Boot 如何热加载jar实现动态插件?

    一.背景 动态插件化编程是一件很酷的事情,能实现业务功能的 解耦 便于维护,另外也可以提升 可扩展性 随时可以在不停服务器的情况下扩展功能,也具有非常好的 开放性 除了自己的研发人员可以开发功能之外, ...

  6. 分享个刚写好的 android 的 ListView 动态加载类,功能全而代码少。

    (转载声明出处:http://www.cnblogs.com/linguanh/) 简介:      该ListView 实现动态加载数据,为了方便用户充分地自定义自己的数据源.点击事件,等核心操作, ...

  7. 关于设置SQLPLUS提示符样式的方法----登陆配置文件,动态加载提示符

    工作中用到 sqlplus mdsoss/mdsoss, 所以来了解一下sqlplus (C shell .cshrc文件里中alisa) 关于设置SQLPLUS提示符样式的方法 12638阅读 1评 ...

  8. shiro不重启动态加载权限

    最近一朋友让我帮他做一个后台权限管理的项目.我就在我原来的项目加加改改但是还是不理想,查了不少资料也走了不了弯路...... shiro基本的配置我就不多说了这个很简单自己查查资料就完成----下面是 ...

  9. OSGI动态加载删除Service bundle

    OSGi模块化框架是很早就出来的一个插件化框架,最早Eclipse用它而出名,但这些年也没有大热虽然OSGi已经发布了版本1到版本5.现在用的最多的,也是本文讲述基于的是Equinox的OSGi实现, ...

随机推荐

  1. response.setHeader()用法

    response.setHeader()下载中文文件名乱码问题 收藏  1. HTTP消息头 (1)通用信息头 即能用于请求消息中,也能用于响应信息中,但与被传输的实体内容没有关系的信息头,如Data ...

  2. C-RAN

    无线接入网(RAN)是移动运营商赖以生存的重要资产.传统的无线接入网具有以下特点: 1. 每一个基站连接若干个固定数量的扇区天线,并覆盖小片区域,每个基站只能处理本小区收发信号: 2. 系统的容量是干 ...

  3. NiceFish的ERROR in AppModule is not an NgModule问题

    大漠老师的angular2新手教程项目,nicefish刚开始下下来运行ng serve --prod --aot 是 出现ERROR in AppModule is not an NgModule ...

  4. Origin软件作图留白过多问题解决

    解决空白过大方法:1.Tools——>Options2.Page——>Copy page setting——>Margin默认是Page,下拉菜单选Border,Clip Borde ...

  5. 简易的解决方式linker command failed with exit code 1 (use -v to see invocation)

    linker command failed with exit code 1 (use -v to see invocation) 遇到这个问题先不要慌,不用纠结是不是自己改动了什么代码导致的. 长话 ...

  6. HDU 1856 并查集

    http://acm.hdu.edu.cn/showproblem.php?pid=1856 More is better Time Limit: 5000/1000 MS (Java/Others) ...

  7. IOS-HTTP协议

    网络由下往上分为 物理层.数据链路层.网络层.传输层.会话层.表示层和应用层. 通过初步的了解,我知道IP协议对应于网络层,TCP协议对应于传输层,而HTTP协议对应于应用层, 三者从本质上来说没有可 ...

  8. Ajax传输对象,集合或数组。

    传输单个对象时: servlet页面 package com.itnba.maya.a; import java.io.IOException; import javax.servlet.Servle ...

  9. Git的origin和master分析

    首先要明确一点,对git的操作是围绕3个大的步骤来展开的(其实几乎所有的SCM都是这样) 1. 从git取数据(git clone) 2. 改动代码 3. 将改动传回git(git push) 这3个 ...

  10. tomcat8启动慢原因及解决办法

    tomcat8在linux下安装使用一段时间后启动非常慢,6分钟左右. 原因是一个随机数生成参数导致的. 处理如下: 修改catalina.sh .配置JRE使用非阻塞的Entropy Source ...