spring.xml配置
<!-- 對數據源進行事務管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="multipleDataSource"></property> </bean>
spring-datasource.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" 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
#mysql jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/quickstart?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=password jdbc.pool.maxActive=50 jdbc.pool.maxIdle=10 jdbc.pool.minIdle=0 jdbc.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")即可!!!