ssm使用注解配置多數據源


在我們剛開始學習編程到初步使用框架開發時,動手去操作數據庫對數據進行增刪查改就覺得很神奇了,

那么我們的框架是不是只能連接一個數據庫呢,當然不是,百度上有許多關於這方面的資料可以學習

jdbc的配置,這里我只是簡單的用1,2區分

#oracle
driver2=oracle.jdbc.driver.OracleDriver
url2=jdbc:oracle:thin:@localhost:1521:ORCL
username2=root
password2=123456

#mysql1
driver1=com.mysql.jdbc.Driver
url1=jdbc:mysql://localhost:3306/jxlz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
username1=root
password1=123456

#mysql2
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/gslz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
username=root
password=123456

這是mybatis的配置,有點多配合上下文及注釋還是可以理解的 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.pskj" annotation-config="true"/><!-- 掃描機制以com.pskj開頭的類直接加入到Spring容器管理器中 -->
    <!-- 引入配置文件 數據庫-->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化連接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連接池最大空閑 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連接池最小空閑 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver1}" />
        <property name="url" value="${url1}" />
        <property name="username" value="${username1}" />
        <property name="password" value="${password1}" />
        <!-- 初始化連接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連接池最大空閑 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連接池最小空閑 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <bean id="dataSource3" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver2}" />
        <property name="url" value="${url2}" />
        <property name="username" value="${username2}" />
        <property name="password" value="${password2}" />
    </bean>

    <!-- 動態DataSource配置    -->
    <bean id="dynamicDataSource" class="com.pskj.GSLZ.utils.dataSource.DynamicDataSource">
        <!--默認數據源  -->
        <property name="defaultTargetDataSource" ref="dataSource3"/>
        <property name="targetDataSources">
            <map key-type="java.lang.String">
                <entry key="dataSource" value-ref="dataSource"/>
                <entry key="dataSource2" value-ref="dataSource2"/>
                <entry key="dataSource3" value-ref="dataSource3"/>
            </map>
        </property>
    </bean>

    <bean id="dataSourceAspect" class="com.pskj.GSLZ.utils.dataSource.DataSwitchAop" />
    <aop:config>
        <aop:aspect ref="dataSourceAspect" >
            <!-- 攔截所有service方法 -->
            <!--我這里實在service上面加的注解,可自行調換  -->
            <aop:pointcut id="dataSourcePointcut" expression="execution(* com.pskj.GSLZ.service..*.*(..))"/>
            <aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
        </aop:aspect>
    </aop:config>
    <!--啟動對@AspectJ注解的支持 , proxy-target-class設置為true表示通知spring使用cglib而不是jdk的來生成代理方法,這樣AOP可以攔截到Controller -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 數據庫連接池 -->
        <!--<property name="dataSource" ref="dataSource" />-->
        <property name="dataSource" ref="dynamicDataSource" />
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*/*.xml"></property>
        <!--加載mybatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.pskj.GSLZ.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- sql會話模版 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype">
        <constructor-arg ref="sqlSessionFactory"/>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--<property name="dataSource" ref="dataSource" />-->
        <property name="dataSource" ref="dynamicDataSource" />
    </bean>

    <!-- cacheManager工廠類,指定ehcache.xml的位置 -->
    <bean id="ehCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml" />
        <property name="shared" value="true"/>
    </bean>

</beans>

還有這個AspectJ等下寫類的時候需要用到它的某些方法

 <dependency>
            <groupId>aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.2</version>
        </dependency>

現在開始寫可以切換數據源的工具類了

DataSource類:

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

//設置注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
@Documented
public @interface DataSource {
    String value() default "";
}

DataSwitchAop類:

import java.lang.reflect.Method;  
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import com.njwangbo.util.DynamicDataSourceHolder;


public class DataSwitchAop {
      /**
     * 攔截目標方法,獲取由@DataSource指定的數據源標識,設置到線程存儲中以便切換數據源
     * 
     * @param point
     * @throws Exception
     */

    public void intercept(JoinPoint point) throws Exception {
        Class<?> target = point.getTarget().getClass();
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 默認使用目標類型的注解,如果沒有則使用其實現接口的注解
        for (Class<?> clazz : target.getInterfaces()) {
            resolveDataSource(clazz, signature.getMethod());
        }
        resolveDataSource(target, signature.getMethod());
    }
    /**
     * 提取目標對象方法注解和類型注解中的數據源標識
     * 
     * @param clazz
     * @param method
     */
    private void resolveDataSource(Class<?> clazz, Method method) {
        try {
            Class<?>[] types = method.getParameterTypes();
            // 默認使用類型注解
            if (clazz.isAnnotationPresent(DataSource.class)) {
                DataSource source = clazz.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.setDataSource(source.value());
            }
            // 方法注解可以覆蓋類型注解
            Method m = clazz.getMethod(method.getName(), types);
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource source = m.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.setDataSource(source.value());
            }
        } catch (Exception e) {
            System.out.println(clazz + ":" + e.getMessage());
        }
    }
}

DynamicDataSourceHolder 類:

public class DynamicDataSourceHolder {
    private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();

    public static String getDataSource() {
        return dataSourceKey.get();
    }


    public static void setDataSource(String dataSource) {
        dataSourceKey.set(dataSource);
    }


    public static void clearDataSource() {
        dataSourceKey.remove();
    }

}

DynamicDataSource類:

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;  

public class DynamicDataSource extends AbstractRoutingDataSource {  
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceHolder.getDataSource();
    }
}  

控制層和sql語句已經寫好

這是service的代碼

    //測試
    @DataSource(value = "dataSource2")
    public PageData listById(PageData pd){
        return (PageData) dao.findForObject("UseMapper.listById",pd);
    }
@DataSource(value = "dataSource2")我們只要改變這個注解里的value值對應我們想查的數據源即可,經測試無論是mysql還是oracle都成功運行


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM