你的位置:首页 > Java教程

[Java教程]spring,mybatis,多数据源配置


spring.

  <!-- 对数据源进行事务管理 -->  <bean id="transactionManager"    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="multipleDataSource"></property>  </bean>

 

spring-datasource.

<??><beans ="http://www.springframework.org/schema/beans"  ="http://www.w3.org/2001/  xsi:schemaLocation="    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">  <!-- alibaba dataSource -->  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"    init-method="init" 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.pool.maxActive}" />    <property name="maxIdle" value="${jdbc.pool.maxIdle}" />    <property name="minIdle" value="${jdbc.pool.minIdle}" />  </bean>    <bean id="dataSource_1" class="com.alibaba.druid.pool.DruidDataSource"    init-method="init" destroy-method="close">    <property name="driverClassName" value="${jdbc.driverClassName}" />    <property name="url" value="${jdbc.url1}" />    <property name="username" value="${jdbc.username}" />    <property name="password" value="${jdbc.password}" />    <property name="maxActive" value="${jdbc.pool.maxActive}" />    <property name="maxIdle" value="${jdbc.pool.maxIdle}" />    <property name="minIdle" value="${jdbc.pool.minIdle}" />  </bean>     <bean id="multipleDataSource" class="cn.tomcat.quickstart.common.utils.MultipleDataSource">    <property name="defaultTargetDataSource" ref="dataSource"/>    <property name="targetDataSources">      <map>        <entry key="dataSource_1" value-ref="dataSource_1"/>      </map>    </property>  </bean></beans>

jdbc.properties

#mysqljdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/quickstart?useUnicode=true&characterEncoding=utf-8jdbc.username=rootjdbc.password=passwordjdbc.pool.maxActive=50jdbc.pool.maxIdle=10jdbc.pool.minIdle=0jdbc.url1=jdbc:mysql://localhost:3306/quickstart1?useUnicode=true&characterEncoding=utf-8

MultipleDataSource.java

package cn.tomcat.quickstart.common.utils;import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class MultipleDataSource extends AbstractRoutingDataSource {  private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();  public static void setDataSourceKey(String dataSource) {    dataSourceKey.set(dataSource);  }  @Override  protected Object determineCurrentLookupKey() {    //System.out.println(dataSourceKey.get());        return dataSourceKey.get();  }}

默认的是datasource数据源,需要切换的时候,

MultipleDataSource.setDataSourceKe("dataSource_1")即可!!!