---
title: "spring多数据源配置"
author: "tooby"
date: "2016-08-28T23:47:05Z"
tags: []
categories: ["编程语言"]
slug: "spring"
draft: false
lastmod: "2016-08-28T23:47:05Z"
id: 2320606
url: "https://tooby.iteye.com/blog/2320606"
---

项目中我们经常会遇到多数据源的问题，尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的，不是配置多个数据源，而是如何能灵活动态的切换数据源。例如在一个[spring](http://lib.csdn.net/base/17 "Java EE知识库")和[hibernate](http://lib.csdn.net/base/17 "Java EE知识库")的框架的项目中，我们在spring配置中往往是配置一个dataSource来连接[数据库](http://lib.csdn.net/base/14 "MySQL知识库")，然后绑定给sessionFactory，在dao层代码中再指定sessionFactory来进行数据库操作。

![](http://img.blog.csdn.net/20130429104020090)

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

![](http://img.blog.csdn.net/20130429105150794)

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

那么正确的做法应该是

![](http://img.blog.csdn.net/20130429111107055)

代码如下：

1\. applicationContext.xml

**\[html]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

001. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
002. &lt;beans xmlns="http://www.springframework.org/schema/beans"
003. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
004. xmlns:cache="http://www.springframework.org/schema/cache"
005. xmlns:context="http://www.springframework.org/schema/context"
006. xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
007. xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
008. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
009. xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
010. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
011. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
012. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
013. http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
014. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
015. http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
016. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
017. http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
018. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
019. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
020. http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
021. http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
022. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
023. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"&gt;
024. &lt;context:annotation-config /&gt;
025. &lt;context:component-scan base-package="com"&gt;&lt;/context:component-scan&gt;
026. &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;
027. &lt;property name="locations"&gt;
028. &lt;list&gt;
029. &lt;value&gt;classpath:com/resource/config.properties&lt;/value&gt;
030. &lt;/list&gt;
031. &lt;/property&gt;
032. &lt;/bean&gt;
033. &lt;bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"
034. destroy-method="close"&gt;
035. &lt;property name="driverClass" value="${dbOne.jdbc.driverClass}" /&gt;
036. &lt;property name="jdbcUrl" value="${dbOne.jdbc.url}" /&gt;
037. &lt;property name="user" value="${dbOne.jdbc.user}" /&gt;
038. &lt;property name="password" value="${dbOne.jdbc.password}" /&gt;
039. &lt;property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" /&gt;
040. &lt;property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" /&gt;
041. &lt;property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" /&gt;
042. &lt;/bean&gt;
043. &lt;bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"
044. destroy-method="close"&gt;
045. &lt;property name="driverClass" value="${dbTwo.jdbc.driverClass}" /&gt;
046. &lt;property name="jdbcUrl" value="${dbTwo.jdbc.url}" /&gt;
047. &lt;property name="user" value="${dbTwo.jdbc.user}" /&gt;
048. &lt;property name="password" value="${dbTwo.jdbc.password}" /&gt;
049. &lt;property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" /&gt;
050. &lt;property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" /&gt;
051. &lt;property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" /&gt;
052. &lt;/bean&gt;
053. &lt;bean id="dynamicDataSource" class="com.core.DynamicDataSource"&gt;
054. &lt;property name="targetDataSources"&gt;
055. &lt;map key-type="java.lang.String"&gt;
056. &lt;entry value-ref="dataSourceOne" key="dataSourceOne"&gt;&lt;/entry&gt;
057. &lt;entry value-ref="dataSourceTwo" key="dataSourceTwo"&gt;&lt;/entry&gt;
058. &lt;/map&gt;
059. &lt;/property&gt;
060. &lt;property name="defaultTargetDataSource" ref="dataSourceOne"&gt;
061. &lt;/property&gt;
062. &lt;/bean&gt;
063. &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;
064. &lt;property name="dataSource" ref="dynamicDataSource" /&gt;
065. &lt;property name="hibernateProperties"&gt;
066. &lt;props&gt;
067. &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
068. &lt;prop key="hibernate.current\_session\_context\_class"&gt;org.springframework.orm.hibernate4.SpringSessionContext&lt;/prop&gt;
069. &lt;prop key="hibernate.show\_sql"&gt;false&lt;/prop&gt;
070. &lt;prop key="hibernate.format\_sql"&gt;true&lt;/prop&gt;
071. &lt;prop key="hbm2ddl.auto"&gt;create&lt;/prop&gt;
072. &lt;/props&gt;
073. &lt;/property&gt;
074. &lt;property name="packagesToScan"&gt;
075. &lt;list&gt;
076. &lt;value&gt;com.po&lt;/value&gt;
077. &lt;/list&gt;
078. &lt;/property&gt;
079. &lt;/bean&gt;
080. &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
081. &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
082. &lt;/bean&gt;
083. &lt;aop:config&gt;
084. &lt;aop:pointcut id="transactionPointCut" expression="execution(* com.dao..\*.\*(..))" /&gt;
085. &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" /&gt;
086. &lt;/aop:config&gt;
087. &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt;
088. &lt;tx:attributes&gt;
089. &lt;tx:method name="add\*" propagation="REQUIRED" /&gt;
090. &lt;tx:method name="save\*" propagation="REQUIRED" /&gt;
091. &lt;tx:method name="update\*" propagation="REQUIRED" /&gt;
092. &lt;tx:method name="delete\*" propagation="REQUIRED" /&gt;
093. &lt;tx:method name="\*" read-only="true" /&gt;
094. &lt;/tx:attributes&gt;
095. &lt;/tx:advice&gt;
096. &lt;aop:config&gt;
097. &lt;aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor"&gt;
098. &lt;aop:pointcut id="daoOne" expression="execution(* com.dao.one.\*.\*(..))" /&gt;
099. &lt;aop:pointcut id="daoTwo" expression="execution(* com.dao.two.\*.\*(..))" /&gt;
100. &lt;aop:before pointcut-ref="daoOne" method="setdataSourceOne" /&gt;
101. &lt;aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" /&gt;
102. &lt;/aop:aspect&gt;
103. &lt;/aop:config&gt;
104. &lt;/beans&gt;

2\. DynamicDataSource.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

1. package com.core;
2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
3. public class DynamicDataSource extends AbstractRoutingDataSource{
4. @Override
5. protected Object determineCurrentLookupKey() {
6. return DatabaseContextHolder.getCustomerType();
7. }
8. }

3\. DatabaseContextHolder.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.core;
02. public class DatabaseContextHolder {
03. private static final ThreadLocal&lt;String&gt; contextHolder = new ThreadLocal&lt;String&gt;();
04. public static void setCustomerType(String customerType) {
05. contextHolder.set(customerType);
06. }
07. public static String getCustomerType() {
08. return contextHolder.get();
09. }
10. public static void clearCustomerType() {
11. contextHolder.remove();
12. }
13. }

4\. DataSourceInterceptor.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.core;
02. import org.aspectj.lang.JoinPoint;
03. import org.springframework.stereotype.Component;
04. @Component
05. public class DataSourceInterceptor {
06. public void setdataSourceOne(JoinPoint jp) {
07. DatabaseContextHolder.setCustomerType("dataSourceOne");
08. }
09. public void setdataSourceTwo(JoinPoint jp) {
10. DatabaseContextHolder.setCustomerType("dataSourceTwo");
11. }
12. }

5\. po实体类

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.po;
02. import javax.persistence.Column;
03. import javax.persistence.Entity;
04. import javax.persistence.Id;
05. import javax.persistence.Table;
06. @Entity
07. @Table(name = "BTSF\_BRAND", schema = "hotel")
08. public class Brand {
09. private String id;
10. private String names;
11. private String url;
12. @Id
13. @Column(name = "ID", unique = true, nullable = false, length = 10)
14. public String getId() {
15. return this.id;
16. }
17. public void setId(String id) {
18. this.id = id;
19. }
20. @Column(name = "NAMES", nullable = false, length = 50)
21. public String getNames() {
22. return this.names;
23. }
24. public void setNames(String names) {
25. this.names = names;
26. }
27. @Column(name = "URL", length = 200)
28. public String getUrl() {
29. return this.url;
30. }
31. public void setUrl(String url) {
32. this.url = url;
33. }
34. }

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.po;
02. import javax.persistence.Column;
03. import javax.persistence.Entity;
04. import javax.persistence.Id;
05. import javax.persistence.Table;
06. @Entity
07. @Table(name = "CITY", schema = "car")
08. public class City {
09. private Integer id;
10. private String name;
11. @Id
12. @Column(name = "ID", unique = true, nullable = false)
13. public Integer getId() {
14. return id;
15. }
16. public void setId(Integer id) {
17. this.id = id;
18. }
19. @Column(name = "NAMES", nullable = false, length = 50)
20. public String getName() {
21. return name;
22. }
23. public void setName(String name) {
24. this.name = name;
25. }
26. }

6\. BrandDaoImpl.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.dao.one;
02. import java.util.List;
03. import javax.annotation.Resource;
04. import org.hibernate.Query;
05. import org.hibernate.SessionFactory;
06. import org.springframework.stereotype.Repository;
07. import com.po.Brand;
08. @Repository
09. public class BrandDaoImpl implements IBrandDao {
10. @Resource
11. protected SessionFactory sessionFactory;
12. @SuppressWarnings("unchecked")
13. @Override
14. public List&lt;Brand&gt; findAll() {
15. String hql = "from Brand";
16. Query query = sessionFactory.getCurrentSession().createQuery(hql);
17. return query.list();
18. }
19. }

7\. CityDaoImpl.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.dao.two;
02. import java.util.List;
03. import javax.annotation.Resource;
04. import org.hibernate.Query;
05. import org.hibernate.SessionFactory;
06. import org.springframework.stereotype.Repository;
07. import com.po.City;
08. @Repository
09. public class CityDaoImpl implements ICityDao {
10. @Resource
11. private SessionFactory sessionFactory;
12. @SuppressWarnings("unchecked")
13. @Override
14. public List&lt;City&gt; find() {
15. String hql = "from City";
16. Query query = sessionFactory.getCurrentSession().createQuery(hql);
17. return query.list();
18. }
19. }

8\. DaoTest.class

**\[java]** [view plain](http://blog.csdn.net/wangpeng047/article/details/8866239 "view plain") [copy](http://blog.csdn.net/wangpeng047/article/details/8866239 "copy")

 

01. package com.test;
02. import java.util.List;
03. import javax.annotation.Resource;
04. import org.junit.Test;
05. import org.junit.runner.RunWith;
06. import org.springframework.test.context.ContextConfiguration;
07. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
08. import org.springframework.test.context.transaction.TransactionConfiguration;
09. import com.dao.one.IBrandDao;
10. import com.dao.two.ICityDao;
11. import com.po.Brand;
12. import com.po.City;
13. @RunWith(SpringJUnit4ClassRunner.class)
14. @ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml")
15. @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
16. public class DaoTest {
17. @Resource
18. private IBrandDao brandDao;
19. @Resource
20. private ICityDao cityDao;
21. @Test
22. public void testList() {
23. List&lt;Brand&gt; brands = brandDao.findAll();
24. System.out.println(brands.size());
25. List&lt;City&gt; cities = cityDao.find();
26. System.out.println(cities.size());
27. }
28. }

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

 

多数据源配置时的重点：

**1. 注意事务拦截器的配置**

这是首要的一条。首先你要明白，Spring的事务管理是与数据源绑定的，一旦程序执行到事务管理的那一层（如service）的话，由于在进入该层之前事务已经通过拦截器开启，因此在该层切换数据源是不行的，明白事务的原理是尤为重要的，我之前的文章中，将切换数据源的拦截器配置在了Dao层是有问题的（因为是示例，所以粗心了，对误导了大家我表示道歉），但提供的思路是没有问题的。

Demo中将切换数据源的拦截器（dataSourceInterceptor）配置在了事务拦截器（txadvice）的上一层，也就是Controller层。

**2. 注意[数据库](http://lib.csdn.net/base/14 "MySQL知识库")表的创建**

一些人喜欢用[hibernate](http://lib.csdn.net/base/17 "Java EE知识库")的自动创建表的功能，但需要注意，在多数据源中，尤其是不同数据库的多数据源，想都自动建表是不行的。因为Hibernate自动建表是在项目启动时触发的，因此只会建立项目配置的默认数据源的表，而其他数据源的表则不会自动创建。大家要注意着点。

**3. Hibernate的数据库方言（dialect）可以忽略**

在多数据源时，方言的设置可以忽略，Hibernate在使用时会自动识别不同的数据库，因此不必纠结这个配置，甚至不配置也可以。

**4. 报No current session错误**

这个是因为使用了sessionFactory.getCurrentSession()导致的，current session是与线程绑定的，一个线程只会开启一个Session（除非使用openSession()就不会报错），因此需要设置session与线程的绑定关系。

Demo中使用了Spring管理Hibernate的session，因此在web.xml中配置了OpenSessionInViewFilter，并在hibernate.cfg.xml中配置了current\_session\_context\_class。【PS：使用Spring管理Hibernate时，可以去掉hibernate.cfg.xml，而全部配置的Spring的配置文件里，即hibernateProperties