项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在spring配置中往往是配置一个dataSource来连接数据库,然后绑定给sessionFactory,在dao层代码中再指定sessionFactory来进行数据库操作。

正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。

可看出在Dao层代码中写死了两个SessionFactory,这样日后如果再多一个数据源,还要改代码添加一个SessionFactory,显然这并不符合开闭原则。

那么正确的做法应该是

代码如下:

1. applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> <context:annotation-config /> <context:component-scan base-package="com"></context:component-scan> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:com/resource/config.properties</value>
</list>
</property>
</bean> <bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${dbOne.jdbc.driverClass}" />
<property name="jdbcUrl" value="${dbOne.jdbc.url}" />
<property name="user" value="${dbOne.jdbc.user}" />
<property name="password" value="${dbOne.jdbc.password}" />
<property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" />
</bean> <bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${dbTwo.jdbc.driverClass}" />
<property name="jdbcUrl" value="${dbTwo.jdbc.url}" />
<property name="user" value="${dbTwo.jdbc.user}" />
<property name="password" value="${dbTwo.jdbc.password}" />
<property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" />
<property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" />
<property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" />
</bean> <bean id="dynamicDataSource" class="com.core.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry value-ref="dataSourceOne" key="dataSourceOne"></entry>
<entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSourceOne">
</property>
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dynamicDataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.po</value>
</list>
</property>
</bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <aop:config>
<aop:pointcut id="transactionPointCut" expression="execution(* com.dao..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" />
</aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice> <aop:config>
<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
<aop:pointcut id="daoOne" expression="execution(* com.dao.one.*.*(..))" />
<aop:pointcut id="daoTwo" expression="execution(* com.dao.two.*.*(..))" />
<aop:before pointcut-ref="daoOne" method="setdataSourceOne" />
<aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" />
</aop:aspect>
</aop:config>
</beans>

2. DynamicDataSource.class

package com.core;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource{

	@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getCustomerType();
} }

3. DatabaseContextHolder.class 

package com.core;

public class DatabaseContextHolder {

	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
} public static String getCustomerType() {
return contextHolder.get();
} public static void clearCustomerType() {
contextHolder.remove();
}
}

 4. DataSourceInterceptor.class

package com.core;

import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component; @Component
public class DataSourceInterceptor { public void setdataSourceOne(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceOne");
} public void setdataSourceTwo(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceTwo");
}
}

 5. po实体类

package com.po;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "BTSF_BRAND", schema = "hotel")
public class Brand { private String id;
private String names;
private String url; @Id
@Column(name = "ID", unique = true, nullable = false, length = 10)
public String getId() {
return this.id;
} public void setId(String id) {
this.id = id;
} @Column(name = "NAMES", nullable = false, length = 50)
public String getNames() {
return this.names;
} public void setNames(String names) {
this.names = names;
} @Column(name = "URL", length = 200)
public String getUrl() {
return this.url;
} public void setUrl(String url) {
this.url = url;
}
}

  

package com.po;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table; @Entity
@Table(name = "CITY", schema = "car")
public class City { private Integer id; private String name; @Id
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} @Column(name = "NAMES", nullable = false, length = 50)
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

  6. BrandDaoImpl.class

package com.dao.one;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository; import com.po.Brand; @Repository
public class BrandDaoImpl implements IBrandDao { @Resource
protected SessionFactory sessionFactory; @SuppressWarnings("unchecked")
@Override
public List<Brand> findAll() {
String hql = "from Brand";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
}

 7. CityDaoImpl.class

package com.dao.two;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository; import com.po.City; @Repository
public class CityDaoImpl implements ICityDao { @Resource
private SessionFactory sessionFactory; @SuppressWarnings("unchecked")
@Override
public List<City> find() {
String hql = "from City";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
}

  8. DaoTest.class

package com.test;

import java.util.List;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration; import com.dao.one.IBrandDao;
import com.dao.two.ICityDao;
import com.po.Brand;
import com.po.City; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
public class DaoTest { @Resource
private IBrandDao brandDao; @Resource
private ICityDao cityDao; @Test
public void testList() {
List<Brand> brands = brandDao.findAll();
System.out.println(brands.size()); List<City> cities = cityDao.find();
System.out.println(cities.size());
}
}

  利用aop,达到动态更改数据源的目的。当需要增加数据源的时候,我们只需要在applicationContext配置文件中添加aop配置,新建个DataSourceInterceptor即可。而不需要更改任何代码。

spring多数据源配置的更多相关文章

  1. 基于xml的Spring多数据源配置和使用

    上一篇讲了<基于注解的Spring多数据源配置和使用>,通过在类或者方法上添加@DataSource注解就可以指定某个数据源.这种方式的优点是控制粒度细,也更灵活. 但是当有些时候项目分模 ...

  2. spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置

    spring BasicDataSource 数据源配置 sqlserver数据库 oracle数据库 mysql数据jdbc配置 jdbc.properties 文件信息如下: ---------- ...

  3. 基于注解的Spring多数据源配置和使用(非事务)

    原文:基于注解的Spring多数据源配置和使用 1.创建DynamicDataSource类,继承AbstractRoutingDataSource package com.rps.dataSourc ...

  4. spring(16)------spring的数据源配置

    在spring中,通过XML的形式实现数据源的注入有三种形式. 一.使用spring自带的DriverManagerDataSource 使用DriverManagerDataSource配置数据源与 ...

  5. 基于注解的Spring多数据源配置和使用

    前一段时间研究了一下spring多数据源的配置和使用,为了后期从多个数据源拉取数据定时进行数据分析和报表统计做准备.由于之前做过的项目都是单数据源的,没有遇到这种场景,所以也一直没有去了解过如何配置多 ...

  6. Spring jndi数据源配置方法

    xml配置: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverMana ...

  7. spring 多数据源配置

    多数据源配置方法: 在配置数据源配置文件中多加一个数据源配置即可: <bean id="dataSource" class="org.apache.commons. ...

  8. Spring 多数据源配置(转)

    转载自:https://www.cnblogs.com/digdeep/p/4512368.html 同一个项目有时会涉及到多个数据库,也就是多数据源.多数据源又可以分为两种情况: 1)两个或多个数据 ...

  9. Spring boot 数据源配置。

    配置文件 : spring boot  配置文件 有两种形式 ,一种是properties文件.一种是yml文件.案列使用properties文件. 数据源的默认配置 : spring boot 约定 ...

随机推荐

  1. msql_DDL_创建table

    • 语法: create table 表名(• 列名1 列类型 [<列的完整性约束>],• 列名2 列类型 [<列的完整性约束>],• ... ... ); • PRIMARY ...

  2. POI导出EXCEL经典实现

    1.Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. .NET的开发人员则 ...

  3. Delphi数组复制

    const AA : arrary[0..4] of byte =(0,1,2,3,4) var BB : arrary[0..4] of byte; begin BB := AA ;   {这样是错 ...

  4. jQuery的deferred对象详解(一)

    最近一段时间,都在研究jquery里面的$.Deffered对象,几天都搞不明白,其中源码的运行机制,网上查找了相关的资料,<jQuery的deferred对象详解>阮一峰老师的文章,里面 ...

  5. [wordpress]wp-api-jwt-auth 尝试添加运行在多站点中 need change

    Hi,Thank you this plugin,because i use this plugin on Wordpress one Network,so the request other api ...

  6. 1369 xth 砍树

    1369 xth 砍树  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 钻石 Diamond 题解       题目描述 Description 在一个凉爽的夏夜,xth 和 ...

  7. OpenFlow概述

    OpenFlow名称里面虽然包括“Flow”,但其并不是“又一个流程引擎”,我们认为世界上的流程引擎已经足够多了,每个流程引擎都各有千秋,有的甚至免费,所以我们不需要再做一个流程引擎,我们做OpenF ...

  8. 各种LICENSE的作用--GET

    许 多开发者和设计者希望把他们的作品作为开源项目共享,他们希望其他人能够利用和共享他们的代码. 而各种开源社区就是因为这个原因而充满活力.开源软件可以用于你能想象得到的任何应用程序,许多web设计人员 ...

  9. JavaScript之菱形打印

    很高兴来到博客园!迈入这座知识的殿堂,实是幸运.这是我的第一篇博客,开启丰富有趣的学习之旅,同时,我希望和大家一起学习一起进步,Let‘s go! <!DOCTYPE html PUBLIC & ...

  10. Java中List与Map初始化的一些写法

    Java的在还没有发现新写法之前时,我一直是这么初始化List跟Map: 代码如下 复制代码  //初始化List    List<string> list = new ArrayList ...