項目需要從其他網站獲取數據,因為是臨時加的需求,在開始項目時沒想到需要多數據源
于是百度了一下,發現只需要改動一下Spring 的applicationContext.xml文件和編寫三個工具類就可以完美實現
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
|
<!-- 多數據源配置 --> <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> <!-- 動態配置數據源 --> <bean id= "dataSource" class = "com.test.utils.DynamicDataSource" > //這里是你項目里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> <!-- 默認使用ds1的數據源 --> <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(設置靜態變量)
1
2
3
4
5
6
|
public class DataSourceType { // 默認數據庫 public static final String SOURCE_ADMIN = "ds1" ; // 第二個數據庫,在applicationContext.xml里的id public static final String SOURCE_PARTNER = "ds2" ; } |
接下來這個是關鍵DynamicDataSource.java 它繼承了AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是實現數據源的route的核心.這里對該方法進行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多數據源的使用實例解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!