`

Spring配置动态数据源

    博客分类:
  • java
阅读更多
代码如下:

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即可。而不需要更改任何代码。

  • 大小: 82.3 KB
分享到:
评论

相关推荐

    Spring配置动态数据源实现读写分离的方法

    本文将详细介绍如何利用Spring配置动态数据源来实现这一功能。 首先,我们需要配置读数据源(readDataSource)和写数据源(writeDataSource)。在示例中,选择了阿里巴巴的Druid数据源,这是一个高性能、易用的...

    spring boot多数据源配置

    2. 配置数据源 在`application.yml`或`application.properties`文件中,为每个数据源定义配置: ```yaml spring: datasource: primary: # 主数据源 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:...

    通过Spring Boot配置动态数据源访问多个数据库的实现代码

    Spring Boot配置动态数据源访问多个数据库实现代码详解 通过Spring Boot配置动态数据源访问多个数据库可以实现数据库的动态增删和数量无限的支持,下面将详细介绍该实现代码的知识点。 数据源配置管理 在Spring ...

    spring配置JNDI数据源

    Spring框架作为一个强大的IoC(Inversion of Control)和AOP(Aspect Oriented Programming)容器,提供了多种配置数据源的方式,其中包括通过JNDI(Java Naming and Directory Interface)来查找和配置数据源。...

    spring数据源配置

    ### Spring 数据源配置详解 #### 一、Spring与数据源简介 在Java企业级应用开发中,数据库操作是必不可少的一部分。Spring框架作为一种流行的轻量级Java应用开发框架,提供了强大的数据库访问支持,其中包括对数据...

    SpringBoot配置多数据源实现动态切换数据源

    本文将深入探讨如何在SpringBoot项目中配置多数据源,并实现数据源的动态切换,帮助你理解和掌握这一核心技能。 首先,我们理解"多数据源"的概念。在SpringBoot应用中,多数据源意味着系统能够连接并操作多个不同的...

    Spring配置MySQL数据源

    连接MYSQL数据库,SPRING配置文件示例。

    spring 动态多数据源配置代码

    - 在Spring配置中,声明`DataSourceTransactionManager`,并指定使用的`DataSource`。 - 实现策略类,用于决定当前应该使用哪个数据源。这通常涉及在运行时获取上下文信息。 5. **动态切换数据源**: 通过自定义...

    spring动态数据源+mybatis分库分表

    在"spring-routing-datasource"这个文件中,可能包含了实现Spring动态数据源的示例代码,包括配置文件、路由数据源的实现以及与MyBatis的集成。通过研究这个例子,你可以更深入地理解如何在实际项目中部署和使用这种...

    spring mvc 配置多数据源

    ### Spring MVC 中配置多数据源详解 在Spring框架中配置多数据源的需求比较常见,尤其在需要处理不同类型的数据库或需要实现数据隔离的应用场景中。本文将详细介绍如何在Spring MVC项目中配置并使用多数据源。 ###...

    真正意义的spring动态切换数据源源码

    2. **配置动态数据源**:在Spring配置文件中,我们需要定义一个`AbstractRoutingDataSource`的子类实例,并为其设置数据源路由表。同时,还需要为每个实际数据源创建一个`DataSource` bean,并将它们添加到路由表中...

    mybatis+spring实现动态切换数据源

    在`mybatis-spring`的配置中,我们指定使用Spring的`SqlSessionFactoryBean`,并将数据源设置为我们的动态数据源。 ```xml &lt;bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"&gt; &lt;!...

    spring 动态切换数据源

    在Spring框架中,动态切换数据源是一项重要的功能,它允许应用程序根据业务需求在多个数据库之间灵活切换。这一特性对于多租户系统、读写分离、分布式数据库等场景尤其有用。以下将详细介绍如何实现Spring的动态数据...

    spring动态选择数据源

    本篇文章将探讨“Spring动态选择数据源”这一主题,它允许我们的应用程序根据业务需求在多个数据源之间灵活切换,这在多租户、读写分离等场景下尤其重要。 首先,理解“数据源”在Spring中的概念。数据源...

    动态数据源实现spring

    在Spring框架中,动态数据源实现是一个重要的特性,它允许应用程序根据特定的条件或用户需求在运行时切换数据源。这种灵活性对于多租户系统、数据隔离或者在不同环境(如开发、测试、生产)之间切换数据库配置尤其...

    Springcloud 多数库 多数据源整合,查询动态切换数据库

    本主题聚焦于在Spring Cloud环境中实现多数据库和多数据源的整合,并且能够动态切换查询的数据库。这是一个复杂但至关重要的需求,特别是在大型企业级应用中,可能需要根据业务逻辑或用户权限连接到不同的数据库。 ...

    springboot连接池、动态配置多数据源连接池,特别适合大数据部门、数据中台服务的多数据源连接池.zip

    1. **配置数据源**:在`application.properties`或`application.yml`文件中,为每个数据源定义相应的属性,如URL、用户名、密码和驱动类名。 2. **创建数据源bean**:利用@ConfigurationProperties绑定配置文件中的...

    Spring3 整合MyBatis3 配置多数据源动态选择SqlSessionFactory详细教程

    Spring3 整合 MyBatis3 配置多数据源动态选择 SqlSessionFactory 详细教程 本教程主要介绍了 Spring3 整合 MyBatis3 配置多数据源动态选择 SqlSessionFactory 的详细教程。下面将详细介绍如何实现 Spring 整合 ...

    Spring配置MySQL数据源2

    用SPRING管理数据源,数据库为oracle

    Spring配置多个数据源

    在开发企业级应用程序时,有时我们需要连接到不止一个数据库,比如主从数据库分离、读写分离、多租户系统等场景...记住,正确管理和配置数据源对于系统的稳定性和性能至关重要,因此在实际操作时一定要仔细检查和测试。

Global site tag (gtag.js) - Google Analytics