• Java spring mvc多数据源配置


    1、首先配置两个数据库
    <bean id="dataSourceA" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="${jdbc.maxActive}" />
    <property name="maxWait" value="${jdbc.maxWait}" />
    </bean>
    <bean id="dataSourceB" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${vjdbc.driverClassName}" />
    <property name="url" value="${vjdbc.url}" />
    <property name="username" value="${vjdbc.username}" />
    <property name="password" value="${vjdbc.password}" />
    <property name="maxActive" value="${jdbc.maxActive}" />
    <property name="maxWait" value="${jdbc.maxWait}" />
    </bean>
    2、再配置一个dataSource 管理 key 值和value值对应,默认选择dataSourceA ,其他配置按照正常的spring mvc 配置即可。
    <bean id="dataSource" class="com.broadengate.util.DynamicDataSource">
    <!-- 通过key-value的形式来关联数据源 -->
    <property name="targetDataSources">
    <map key-type="java.lang.String">
    <entry value-ref="dataSourceA" key="dataSourceA"></entry>
    <entry value-ref="dataSourceB" key="dataSourceB"></entry>
    </map>
    </property>
    <property name="defaultTargetDataSource" ref="dataSourceA" >
    </property>
    </bean>
    3、sessionFactory 中使用 dataSource做数据源。
    4、新建一个DynamicDataSource类继承AbstractRoutingDataSource。
    public class DynamicDataSource extends AbstractRoutingDataSource{
    public static final String DATA_SOURCE_A = "dataSourceA";
    public static final String DATA_SOURCE_B = "dataSourceB";
    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();
    }
    @Override
    protected Object determineCurrentLookupKey() {
    return getCustomerType();
    }
    }
    5、切换数据源,这一步必须在进入业务层之前切换。
    DynamicDataSource.setCustomerType(DynamicDataSource.DATA_SOURCE_A);
    作者:李果

    Java spring mvc多数据源配置
    http://www.itpub.net/thread-1906608-1-1.html
    (出处: ITPUB论坛-中国最专业的IT技术社区)

  • 相关阅读:
    【Linux】PuTTY----------windows访问Linux 快捷方便
    接口测试、概念及常用方法小结
    设计模式
    事务
    Struts2技术详解
    message from server: "Host 'xxx' is not allowed to connect to this MySQL server的解决
    Java中多态性的实现
    应用上下文webApplicationContext
    ubuntu 12.04下访问windows共享文件夹
    排序问题分析
  • 原文地址:https://www.cnblogs.com/orac/p/6830188.html
Copyright © 2020-2023  润新知