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

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

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

那么正确的做法应该是

代码如下:

1. applicationContext.xml<?xml version="1.0" encoding="UTF-8"?>

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">

classpath:com/resource/config.properties

destroy-method="close">

destroy-method="close">

org.hibernate.dialect.MySQLDialect

org.springframework.orm.hibernate4.SpringSessionContext

false

true

create

com.po

2. DynamicDataSource.classpackage com.core;

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

public class DynamicDataSource extends AbstractRoutingDataSource{

@Override

protected Object determineCurrentLookupKey() {

return DatabaseContextHolder.getCustomerType();

}

}

3. DatabaseContextHolder.classpackage com.core;

public class DatabaseContextHolder {

private static final ThreadLocal contextHolder = new ThreadLocal();

public static void setCustomerType(String customerType) {

contextHolder.set(customerType);

}

public static String getCustomerType() {

return contextHolder.get();

}

public static void clearCustomerType() {

contextHolder.remove();

}

}

4. DataSourceInterceptor.classpackage 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.classpackage 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 findAll() {

String hql = "from Brand";

Query query = sessionFactory.getCurrentSession().createQuery(hql);

return query.list();

}

}

7. CityDaoImpl.classpackage 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 find() {

String hql = "from City";

Query query = sessionFactory.getCurrentSession().createQuery(hql);

return query.list();

}

}

8. DaoTest.classpackage 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 brands = brandDao.findAll();

System.out.println(brands.size());

List cities = cityDao.find();

System.out.println(cities.size());

}

}

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多深入理解spring多数据源配置相关文章请关注PHP中文网!

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

java spring多数据源配置文件_深入理解spring多数据源配置相关推荐

  1. java注解的执行顺序_深入理解Spring的@Order注解和Ordered接口

    前言 Spring的@Order注解或者Ordered接口大家都知道是控制顺序的,那么它们到底是控制什么顺序的?是控制Bean的注入顺序,还是Bean的实例化顺序,还是Bean的执行顺序呢?那么我们先 ...

  2. java spring boot 注解验证_如何理解Java原生注解和Spring 各种注解?

    作者:digdeep .cnblogs.com/digdeep/p/4525567.html 导引 Spring中的注解大概可以分为两大类: spring的bean容器相关的注解,或者说bean工厂相 ...

  3. java 异步调用 事务_深入理解Spring注解@Async解决异步调用问题

    序言:Spring中@Async 根据Spring的文档说明,默认采用的是单线程的模式的.所以在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的. 那么当多个任务的执行势必会相互影响. ...

  4. 不同类的方法 事务问题_深入理解 Spring 事务原理

    Spring事务的基本原理 Spring事务的本质其实就是数据库对事务的支持,没有数据库的事务支持,spring是无法提供事务功能的.对于纯JDBC操作数据库,想要用到事务,可以按照以下步骤进行: 获 ...

  5. idea中生成spring的 xml配置文件_【132期】面试再被问到Spring容器IOC初始化过程,就拿这篇文章砸他~...

    点击上方"Java面试题精选",关注公众号 面试刷图,查缺补漏 >>号外:往期面试题,10篇为一个单位归置到本公众号菜单栏->面试题,有需要的欢迎翻阅 阶段汇总集 ...

  6. python ioc框架_轻松理解 Spring 中的 IOC

    Spring 简介 Spring 是一个开源的轻量级的企业级框架,其核心是反转控制 (IoC) 和面向切面 (AOP) 的容器框架.我们可以把 Spring 看成是对象的容器,容器中可以包含很多对象, ...

  7. gateway oauth2 对称加密_深入理解Spring Cloud Security OAuth2及JWT

    因项目需要,需要和三方的oauth2服务器进行集成.网上关于spring cloud security oauth2的相关资料,一般都是讲如何配置,而能把这块原理讲透彻的比较少,这边自己做一下总结和整 ...

  8. springcloud 组件_深入理解 Spring Cloud 核心组件与底层原理

    新人大礼包,30G Java架构资料,免费领取​zhuanlan.zhihu.com 一.Spring Cloud核心组件:Eureka Netflix Eureka Eureka详解 1.服务提供者 ...

  9. java怎么设置404界面_如何使用Spring MVC显示自定义的404 Not Found页面

    本篇文章给大家带来的内容是关于如何使用Spring MVC显示自定义的404 Not Found页面,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 不知道大家对千篇一律的404 No ...

最新文章

  1. 获得杰青的北大教授,竟被本科生质疑硕士毕业双非高校也能任教?网友:荒唐!...
  2. 玩转HTML5移动页面(转自http://tqtan.com/)
  3. Centos7 vim/vi的使用
  4. pku 1925 Spiderman DP
  5. 数据科学竞赛-房价预测
  6. Docker中Maven私服的搭建
  7. Python程序执行顺序
  8. 主从复制中忽略库的参数
  9. ST环境进行测试时,事前需要考虑的问题
  10. java 新手入门电子书_3款针对初学者的免费Java电子书
  11. 开源、绿色,解压即可运行的数据库连接工具推荐
  12. 计算机应用职业生涯规划,计算机应用技术职业规划书|计算机应用专业个人职业规划...
  13. 2018年腾讯校招产品群面体会
  14. python3 [入门基础实战] 爬虫入门之刷博客浏览量
  15. mac android 文件管理器,PC和Mac浏览安卓手机上文件最快的方式,只需两步
  16. 想学Docker?我教你啊~
  17. JPA之SQL修改语句
  18. linux系统发qq邮箱文件,Linux打印文件和发送邮件
  19. 栈的详解(C/C++数据结构)
  20. 南京软件测试自学英语,南京软件测试培训班怎么样?南京软件测试培训班学什么?...

热门文章

  1. win7+opencv3.0.0+vs2010 安装及配置
  2. git tag打标签常用命令
  3. 连载:面向对象葵花宝典:思想、技巧与实践(34) - DIP原则
  4. Python——eventlet.wsgi
  5. LeetCode: Word Search
  6. 事后分析报告(M2阶段)
  7. poj 1270 Following Orders
  8. 在Silverlight中使用ESFramework-- ESFramework 4.0 快速上手(05)
  9. 走向ASP.NET架构设计--第一章:走向设计
  10. Ansible 系统概述与部署(1)