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);