項(xiàng)目需要從其他網(wǎng)站獲取數(shù)據(jù),因?yàn)槭桥R時(shí)加的需求,在開始項(xiàng)目時(shí)沒想到需要多數(shù)據(jù)源
于是百度了一下,發(fā)現(xiàn)只需要改動(dòng)一下Spring 的applicationContext.xml文件和編寫三個(gè)工具類就可以完美實(shí)現(xiàn)
applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!-- 多數(shù)據(jù)源配置 --> <bean id= "ds1" class = "org.apache.commons.dbcp.BasicDataSource" > <property name= "driverClassName" value= "${jdbc.driverClassName}" /> <property name= "url" value= "${jdbc.url}" /> <property name= "username" value= "${jdbc.username}" /> <property name= "password" value= "" /> </bean> <bean id= "ds2" class = "org.apache.commons.dbcp.BasicDataSource" > <property name= "driverClassName" value= "" /> <property name= "url" value= "" /> <property name= "username" value= "" /> <property name= "password" value= "" /> </bean> <!-- 動(dòng)態(tài)配置數(shù)據(jù)源 --> <bean id= "dataSource" class = "com.test.utils.DynamicDataSource" > //這里是你項(xiàng)目里DynamicDataSource.java的路徑 <property name= "targetDataSources" > <map key-type= "java.lang.String" > <entry value-ref= "ds_admin" key= "ds1" ></entry> <entry value-ref= "ds_partner" key= "ds2" ></entry> </map> </property> <!-- 默認(rèn)使用ds1的數(shù)據(jù)源 --> <property name= "defaultTargetDataSource" ref= "ds_admin" ></property> </bean> |
DataSourceContextHolder.java
1
2
3
4
5
6
7
8
9
10
11
12
|
public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDbType(String dbType) { contextHolder.set(dbType); } public static String getDbType() { return ((String) contextHolder.get()); } public static void clearDbType() { contextHolder.remove(); } } |
DataSourceType.java(設(shè)置靜態(tài)變量)
1
2
3
4
5
6
|
public class DataSourceType { // 默認(rèn)數(shù)據(jù)庫 public static final String SOURCE_ADMIN = "ds1" ; // 第二個(gè)數(shù)據(jù)庫,在applicationContext.xml里的id public static final String SOURCE_PARTNER = "ds2" ; } |
接下來這個(gè)是關(guān)鍵DynamicDataSource.java 它繼承了AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是實(shí)現(xiàn)數(shù)據(jù)源的route的核心.這里對該方法進(jìn)行Override。
1
2
3
4
5
6
7
|
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDbType(); } } |
以上所述是小編給大家介紹的Spring MVC Mybatis多數(shù)據(jù)源的使用實(shí)例解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!