1. 程式人生 > >spring多資料來源配置 簡單明瞭

spring多資料來源配置 簡單明瞭

來源地址https://blog.csdn.net/ll535299/article/details/78203634

 

1.首先在config.properties檔案中配置兩個資料庫連線的基本資料。這個省略了 
2.在spring配置檔案中配置這兩個資料來源: 
資料來源1

 <!-- initialSize初始化時建立物理連線的個數0  maxActive最大連線池數量8 minIdle最小連線池數量0-->
    <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" scope="singleton">
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="url" value="${jdbc.url}" />
        <property name="initialSize" value="${jdbc.init}" />
        <property name="maxActive" value="${jdbc.max}" />
        <property name="minIdle" value="${jdbc.min}" />
    </bean>

 

資料來源2

<bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" scope="singleton">
        <property name="username" value="${jdbc.username2}" />
        <property name="password" value="${jdbc.password2}" />
        <property name="url" value="${jdbc.url2}" />
        <property name="initialSize" value="${jdbc.init2}" />
        <property name="maxActive" value="${jdbc.max2}" />
        <property name="minIdle" value="${jdbc.min2}" />
    </bean>

 

3.自定義一個數據源類,該類繼承 org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource 
並重寫determineCurrentLookupKey()方法 
3.1程式碼如下

public class RoutingDataSource extends AbstractRoutingDataSource  {

     @Override
     protected Object determineCurrentLookupKey() {
            return DataSourceHolder.getDataSourceType();
     }

}

 

3.2將該類交由sping管理,其在spring配置檔案中配置如下

<bean id="dataSource" class="com.coe.exp.core.dataSource.RoutingDataSource">
        <!-- 為targetDataSources注入兩個資料來源 -->
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="ds1" value-ref="dataSource1"/>
                <entry key="ds2" value-ref="dataSource2"/>
            </map>
        </property>
        <!-- 為指定資料來源RoutingDataSource注入預設的資料來源-->
         <property name="defaultTargetDataSource" ref="dataSource1"/>
    </bean>

3.3spring其他的配置如下

<!-- MyBatis配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 把dataSource注入給sqlSessionFactory -->
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.coe.exp.core.ent" />
        <!-- 指定mapper.xml的位置 -->
        <property name="mapperLocations" >
                <array>
                    <value>classpath:com/coe/exp/core/xml/**/*.xml</value>
                    <value>classpath:com/coe/exp/xml/**/*.xml</value>
            </array>
        </property>
        <!-- 指定myBatis配置檔案的位置 -->
        <property name="configLocation" value="classpath:mybatis/sqlmapconfig.xml" />
    </bean>


    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.coe.exp.core.mapper,com.coe.exp.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </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="insert*" propagation="REQUIRED"/>
             <tx:method name="save*" propagation="REQUIRED"/>
             <tx:method name="update*" propagation="REQUIRED"/>
             <tx:method name="delete*" propagation="REQUIRED"/>
             <tx:method name="remove*" propagation="REQUIRED"/>
             <tx:method name="add*" propagation="REQUIRED"/>
             <tx:method name="find*" propagation="SUPPORTS"/>
             <tx:method name="get*" propagation="SUPPORTS"/>
         </tx:attributes>
     </tx:advice>

     <aop:config>
         <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.coe.exp.dao..*Impl.*(..))" order="2"/>
         <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.coe.exp.core.dao..*Impl.*(..))" order="3"/>
     </aop:config>

    <!-- 註解方式配置事物   -->
    <tx:annotation-driven transaction-manager="transactionManager" />

<!-- 引入屬性檔案 -->
    <context:property-placeholder location="classpath:config.properties" />
    <!-- 自動掃描(自動注入) -->
    <context:component-scan base-package="com.coe.exp,mm" annotation-config="true">  
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <context:component-scan base-package="com.coe,mm"/>  
    <!-- 自動掃描定時任務 -->
    <task:annotation-driven/> 
    <!-- spring自動建立代理,植入切面,proxy-target-class屬性,預設為false,表示使用jdk動態代理織入增強,當配為<aop:aspectj-autoproxy  
    poxy-target-class="true"/>時,表示使用CGLib動態代理技術織入增強。不過即使proxy-target-class設定為false,如果目標類沒有宣告介面,則spring將自動使用CGLib動態代理。 -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <import resource="../shiro/spring-shiro.xml"/>

4.編寫一個數據源持有類DataSourceHolder

public class DataSourceHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 

    /**
     * @Description: 設定資料來源型別
     * @param dataSourceType  資料庫型別
     * @return void
     * @throws
     */ 
    public static void setDataSourceType(String dataSourceType) { 
        contextHolder.set(dataSourceType); 
    } 

    /**
     * @Description: 獲取資料來源型別
     * @param 
     * @return String
     * @throws
     */ 
    public static String getDataSourceType() { 
        return contextHolder.get(); 
    } 

    /**
     * @Description: 清除資料來源型別
     * @param 
     * @return void
     * @throws
     */ 
    public static void clearDataSourceType() { 
        contextHolder.remove(); 
    }
}

5.自定義註解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Component;

/**
 * 資料來源
 * 
 * @author llb 2017-03-30
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface DataSource {

    String value() default "";

}

6.動態切換資料來源

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Repository;

import com.coe.exp.core.dataSource.DataSourceHolder;


@Order(1)
@Aspect  
@Repository
public class DataSourceAspect {

    @Pointcut("execution(* com..dao..*Impl.*(..))")
    private void anyMethod() {  
    }

    @AfterReturning(value = "anyMethod()", returning = "result")  
    public void afterReturning(JoinPoint joinPoint,Object result){
        DataSourceHolder.clearDataSourceType();
    }

    @Before(value="anyMethod()")
    public void before(JoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();  
        Method method = methodSignature.getMethod();  
        //如果方法體上使用了DataSource註解
        if (method.isAnnotationPresent(DataSource.class)) {
            //獲取該方法上的註解名
            DataSource datasource = method.getAnnotation(DataSource.class);
            //將方法體上的註解的值賦予給DataSourceHolder資料來源持有類
            DataSourceHolder.setDataSourceType(datasource.value());
        }
    }

}

7.若方法體上沒有註解,則都是使用預設資料來源,如果有以下註解,則使用指定的資料來源

/**
     * 查詢哲盟資料庫中所有狀態正常的客戶餘額
     * @return
     * @author mxl
     * @version 2017年8月16日下午1:30:06
     */
    @DataSource("ds2")
    public List<CustomerBalanceEnt> getAllCustBalanceByZm(){
        return customerBalanceMapper.getAllCustBalanceByZm();
    }

上面這個方法就是使用“ds2”;