Spring+Mybatis多数据源配置(四)——AbstractRoutingDataSource实现数据源动态切换

本文介绍如何使用Spring的AbstractRoutingDataSource实现动态数据源切换,通过自定义类DataSources并实现determineCurrentLookupKey方法来确定当前的数据源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候需要在程序中动态切换数据源,那么这个系列的之前的博文所阐述的方法就不再使用了,总不能通过程序更改config.properties文件的dataSource的值,然后再重启web服务器以便加载applicationContext.xml文件。这里讲诉的是如何利用AbstractRoutingDataSource进行数据源动态切换。

首先上applicationContext.xml文件:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.         xmlns:context="http://www.springframework.org/schema/context"  
  5.         xmlns:aop="http://www.springframework.org/schema/aop"   
  6.         xmlns:tx="http://www.springframework.org/schema/tx"   
  7.         xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans  
  9.         classpath:/org/springframework/beans/factory/xml/spring-beans-3.0.xsd  
  10.         http://www.springframework.org/schema/aop   
  11.         classpath:/org/springframework/aop/config/spring-aop-3.0.xsd  
  12.         http://www.springframework.org/schema/context  
  13.         classpath:/org/springframework/context/config/spring-context-3.0.xsd  
  14.         http://www.springframework.org/schema/tx   
  15.         classpath:/org/springframework/transaction/config/spring-tx-3.0.xsd">  
  16.   
  17.     <!-- IoC配置 -->  
  18.     <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->  
  19.     <context:component-scan base-package="com.shr.dao" />  
  20.     <context:component-scan base-package="com.shr.service" />  
  21.       
  22.     <!-- DAO配置 -->  
  23.     <context:property-placeholder location="classpath:config.properties"/>  
  24.     <bean id="mysql" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  25.         <property name="driverClassName"     value="${mysql_driver}"/>  
  26.         <property name="url"         value="${mysql_url}"/>  
  27.         <property name="username"    value="${mysql_username}"/>  
  28.         <property name="password"    value="${mysql_password}"/>  
  29.     </bean>  
  30.     <bean id="oracle" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  31.         <property name="driverClassName"     value="${ora_driver}"/>  
  32.         <property name="url"         value="${ora_url}"/>  
  33.         <property name="username"    value="${ora_username}"/>  
  34.         <property name="password"    value="${ora_password}"/>  
  35.     </bean>  
  36.       
  37.     <bean id="dataSource" class="com.shr.dao.datasource.DataSources">  
  38.         <property name="targetDataSources">  
  39.             <map key-type="java.lang.String">  
  40.                 <entry value-ref="mysql" key="MYSQL"></entry>  
  41.                 <entry value-ref="oracle" key="ORACLE"></entry>  
  42.             </map>  
  43.         </property>  
  44.         <property name="defaultTargetDataSource" ref="mysql"></property>  
  45.     </bean>  
  46.   
  47.     <bean id="vendorProperties"  
  48.         class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
  49.         <property name="properties">  
  50.             <props>  
  51.                 <prop key="Oracle">oracle</prop>  
  52.                 <prop key="MySQL">mysql</prop>  
  53.             </props>  
  54.         </property>  
  55.     </bean>  
  56.   
  57.     <bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider">  
  58.         <property name="properties" ref="vendorProperties" />  
  59.     </bean>  
  60.     <bean name="myBatisSQLInterceptor" class="com.shr.dao.MyBatisSQLInterceptor"></bean>  
  61.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  62.         <property name="dataSource" ref="dataSource" />  
  63.         <property name="typeAliasesPackage" value="com.shr.dao.pojo,com.shr.dao.model" />  
  64.         <property name="databaseIdProvider" ref="databaseIdProvider" />  
  65.         <property name="mapperLocations">  
  66.             <list>  
  67.                 <value>classpath:com/shr/dao/resources/mappers/*_mapper.xml</value>  
  68.             </list>  
  69.         </property>  
  70.         <!-- <property name="configLocation" value="/WEB-INF/mybatis-config.xml"/> -->  
  71.         <property name="typeHandlersPackage" value="com.shr.dao" />  
  72.         <property name="plugins">  
  73.             <list>  
  74.                 <ref bean="myBatisSQLInterceptor"/>  
  75.             </list>  
  76.         </property>  
  77.     </bean>  
  78.       
  79.     <!-- 配置事务管理器 -->  
  80.     <tx:annotation-driven/>  
  81.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  82.         <property name="dataSource" ref="${dataSource}"/>  
  83.     </bean>  
  84.       
  85.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  86.         <property name="basePackage" value="com.shr.dao.mapper"/>  
  87.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>   
  88.         <!-- <property name="markerInterface" value="com.shr.dao.mapper.ITemplateMapper"/> -->  
  89.     </bean>  
  90. </beans>  
我们可以观察到文件中多了一段:

[html]  view plain  copy
  1. <bean id="dataSource" class="com.shr.dao.datasource.DataSources">  
  2.     <property name="targetDataSources">  
  3.         <map key-type="java.lang.String">  
  4.             <entry value-ref="mysql" key="MYSQL"></entry>  
  5.             <entry value-ref="oracle" key="ORACLE"></entry>  
  6.         </map>  
  7.     </property>  
  8.     <property name="defaultTargetDataSource" ref="mysql"></property>  
  9. </bean>  
而且sqlSessionFactory的dataSource是关联到上面这段内容的,而不是通过${dataSource}读取config.properties文件的内容获取的。

这个com.shr.dao.datasource.DataSources是自定义的类,继承自AbstractRoutingDataSource类,实现其determineCurrentLookupKey()方法。

代码如下:

[java]  view plain  copy
  1. package com.shr.dao.datasource;  
  2. import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  
  3. public class DataSources extends AbstractRoutingDataSource  
  4. {  
  5.     @Override  
  6.     protected Object determineCurrentLookupKey()  
  7.     {  
  8.         return DataSourceSwitch.getDataSourceType();  
  9.     }  
  10. }  
[java]  view plain  copy
  1. package com.shr.dao.datasource;  
  2.   
  3. public class DataSourceSwitch  
  4. {  
  5.     private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();  
  6.       
  7.     public static void setDataSourceType(String dataSourceType)  
  8.     {  
  9.         contextHolder.set(dataSourceType);  
  10.     }  
  11.       
  12.     public static String getDataSourceType()  
  13.     {  
  14.         return contextHolder.get();  
  15.     }  
  16.       
  17.     public static void clearDataSourceType()  
  18.     {  
  19.         contextHolder.remove();  
  20.     }  
  21. }  
[java]  view plain  copy
  1. package com.shr.dao.datasource;  
  2.   
  3. public class DataSourceInstances  
  4. {  
  5.     public static final String MYSQL="MYSQL";  
  6.     public static final String ORACLE="ORACLE";  
  7. }  
同样,我们通过一个junit测试用例进行验证:

[java]  view plain  copy
  1. package com.shr.dao.datasource;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.inject.Inject;  
  6.   
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.springframework.test.context.ContextConfiguration;  
  10. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
  11. import org.springframework.test.context.transaction.TransactionConfiguration;  
  12. import org.springframework.transaction.annotation.Transactional;  
  13.   
  14. import com.shr.dao.datasource.DataSourceInstances;  
  15. import com.shr.dao.datasource.DataSourceSwitch;  
  16. import com.shr.dao.model.userManage.UserListInfo;  
  17. import com.shr.service.userManage.UserManageService;  
  18.   
  19. @RunWith(SpringJUnit4ClassRunner.class)  
  20. @ContextConfiguration("file:WebContent/WEB-INF/applicationContext.xml")  
  21. @Transactional  
  22. @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=false)  
  23. public class DynamicDataSourceTest  
  24. {  
  25.     @Inject  
  26.     private UserManageService userManageService;  
  27.       
  28.     @Test  
  29.     public void test()  
  30.     {  
  31.         DataSourceSwitch.setDataSourceType(DataSourceInstances.MYSQL);  
  32.         List<UserListInfo> list = userManageService.getUserListInfo();  
  33.         for(UserListInfo user : list)  
  34.         {  
  35.             System.out.println(user.getUser_name());  
  36.         }  
  37.     }  
  38. }  
通过改变 DataSourceSwitch.setDataSourceType(DataSourceInstances.ORACLE); 可以转换不同的数据源.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值