原文:http://blog.csdn.net/fhx007/article/details/12530735
----------------------------------------------------------------------------------
直接看spring的配置吧
 
 
 <!-- 数据源配置 -->  
 <bean id="ds1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
     <property name="driverClassName" value="Oracle.jdbc.driver.OracleDriver" />  
     <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />  
     <property name="username" value="test" />  
     <property name="password" value="test" />  
     <property name="defaultAutoCommit" value="false"></property>  
 </bean>  
   
 <bean id="ds2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
     <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />  
     <property name="username" value="test" />  
     <property name="password" value="test" />  
     <property name="defaultAutoCommit" value="false"></property>  
 </bean>  
   
  <bean id="dataSource" class="app.platform.mybatis.DynamicDataSource">  
     <property name="targetDataSources">  
         <map key-type="Java.lang.String">  
             <entry value-ref="ds1" key="ds1"></entry>  
             <entry value-ref="ds2" key="ds2"></entry>  
         </map>  
     </property>  
     <property name="defaultTargetDataSource" ref="ds1"></property>      <!-- 默认使用ds1的数据源 -->
 </bean>  
 
 
 <!-- mybatis配置 -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />
 <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
 <property name="mapperLocations" value="classpath*:app/mapper/**/*.xml"/>
 </bean>
 
 <!-- 事务管理器配置,单数据源事务 -->
 <bean id="transactionManager"
 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource" />
 </bean>
 
 <!-- 事务拦截的类及方法 -->
 <tx:advice id="txAdvice" transaction-manager="transactionManager">
 <tx:attributes>
 <tx:method name="get*" read-only="true" />
 <tx:method name="find*" read-only="true" />
 <tx:method name="query*" read-only="true" />
 <tx:method name="is*" read-only="true" />
 <tx:method name="do*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
 <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
 <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
 <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" />
 </tx:attributes>
 </tx:advice>
 <aop:config proxy-target-class="true">
 <aop:advisor pointcut="execution(* app..service..*.*(..))" advice-ref="txAdvice" />
 </aop:config>
 
重点是上面的数据源配置
 
 
下面的类是在数据源中用到的
 package app.platform.mybatis;
 
 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 
 public class DynamicDataSource extends AbstractRoutingDataSource {  
     @Override  
     protected Object determineCurrentLookupKey() {  
         return DataSourceContextHolder.getDbType();  
     }  
 }
 
 
 
 package app.platform.mybatis;
 
 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();  
     }  
 }  
 
 
 
这样就可以了,下面是一个单元测试的例子
 public class Test{
 
 @Autowired
 private TestService testService;
 
 
 @Test  
 public void addTest() throws Exception {  
    User user = new User();  
    user.setUsername("admin");  
    user.setPassword("123456");  
    
    DataSourceContextHolder.setDbType("ds2");     //注意这里在调用service前切换到ds2的数据源
  
    testService.add(user);  
 }  
 }
 
 
 
 最主要的变化是DynamicDataSource 类,这个类继承了AbstractRoutingDataSource,我们再继续考察,发现这个类实现了datasource这个接口。 
 
 再仔细研究,发现我配置了多个数据源给DynamicDataSource,默认的数据源是ds1。 
 我们研究下AbstractRoutingDataSource类的代码,主要是两个实现datasource的方法 
 
- public Connection getConnection() throws SQLException {
- return determineTargetDataSource().getConnection();
- }
- public Connection getConnection(String username, String password) throws SQLException {
- return determineTargetDataSource().getConnection(username, password);
- }
根据这段代码发现主要玄机都在determineTargetDataSource()方法上。
- protected DataSource determineTargetDataSource() {
- Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
- Object lookupKey = determineCurrentLookupKey();
- DataSource dataSource = this.resolvedDataSources.get(lookupKey);
- if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
- dataSource = this.resolvedDefaultDataSource;
- }
- if (dataSource == null) {
- throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
- }
- return dataSource;
- }
根据这段代码发现,首先在使用数据源之前,首先判断使用数据源的key,也就是我们配置给
- private Map<Object, Object> targetDataSources;
这个map中的key值,找到key值之后再找到对应的datasource然后并使用这个数据源。
从上面我们发现,实际上DynamicDataSource只是在内部封装了数据源,然后调用它,只不过在内部他加了一些控制而已。(此处不知道是否可以理解为代理模式)
再深一步想想,此处使用的orm层是mybatis,如果换成hibernate呢,或者jdbctemplate呢。
实际上这个方法都适用。
 
 
