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技術社區)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM