ssm框架实现多数据源的配置,本人亲测,项目正在使用。

1、这是项目的目录结构

2、Web.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">


<!-- 初始化spring容器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:spring/applicationContext-*.xml,
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
扫描Springmvc
-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截所有 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


<!-- post乱码处理-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

3、sqlMapConfig.xml

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


    <typeAliases>
        <!-- 扫描当前包下的所有的类  类型的名称就是类名(首字母大写或小写) -->
        <package name="com.gongsi.bean"/>
    </typeAliases>
    
</configuration>

4、applicationContext-core.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
     
    <!-- 开启注解模式 -->
<context:annotation-config />
<!-- 扫描我们 action service dao 文件 -->
<context:component-scan base-package="com.gongsi.*"></context:component-scan>
 
<!-- 物理数据源  -->
<!--我是用的SQLServer数据库,可自行调换  -->
<bean id="MydataSource_1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
<property name="url" value="jdbc:sqlserver://localhost:****;DatabaseName=**"></property>
<property name="username" value="**"></property>
<property name="password" value="****"></property>
</bean>

<bean id="MydataSource_2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
<property name="url" value="jdbc:sqlserver://localhost:****;DatabaseName=****"></property>
<property name="username" value="**"></property>
<property name="password" value="****"></property>
</bean>
<bean id="dataSource" class="com.gongsi.util.DynamicDataSource">  
    <property name="targetDataSources">  
        <map key-type="java.lang.String">
            <!-- 指定lookupKey和与之对应的数据源 -->
            <entry key="1" value-ref="MydataSource_1"></entry>  
            <entry key="2" value-ref="MydataSource_2"></entry>  
        </map>  
    </property>  
    <!-- 这里可以指定默认的数据源 -->
    <property name="defaultTargetDataSource" ref="MydataSource_2" />  
</bean>
     <!-- 通过IOC管理sqlSessionFactory -->   
     <bean id="MysqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <property name="dataSource" ref="dataSource"></property>
           <!-- 加载我们的mybatis的总控制文件 -->
           <property name="configLocation" value="classpath:mapper/sqlMapConfig.xml"></property>
     </bean>
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    
          <!--          
                            扫描当前包下的所有mapper 如果映射关系文件不再一个包中,我们多个包之间使用逗号分隔                   
                            在程序中获取接口代理的名称就是当前接口的首字母小写形式
          -->         
          <property name="basePackage" value="com.gongsi.mapper"></property>
          <!-- 使用sqlSessionFactory -->
          <property name="sqlSessionFactoryBeanName" value="MysqlSessionFactory"></property>
     </bean>
</beans> 

5、applicationContext-transaction.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
    <!-- 声明spring中的事务管理器 -->
<bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
    <tx:advice id="Myadvice" transaction-manager="manager">
    <tx:attributes>
        <!-- REQUIRED 事务的传播性,如果没有事务给当前的方法开启一个新的事务 -->     
        <tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
        <!-- 這個類型的方法不需要使用事務 -->
        <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>                         
    </tx:attributes>
</tx:advice>


<aop:aspectj-autoproxy></aop:aspectj-autoproxy>  
   <bean id="dataSourceAspect" class="com.gongsi.util.DataSourceAspect" />
    <aop:config>
        <aop:aspect ref="dataSourceAspect" >
            <!-- 拦截所有service方法 -->
            <!--我这里实在Mapper上面加的注解,可自行调换  -->
            <aop:pointcut id="dataSourcePointcut" expression="execution(* com.gongsi.mapper..*.*(..))"/>
            <aop:before pointcut-ref="dataSourcePointcut" method="intercept" />
        </aop:aspect>
    </aop:config>
</beans> 

6、springmvc.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.2.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<mvc:annotation-driven/>
<!--自动扫描,使springMVC认为包下用了@controller注解的类是控制器-->
      <context:component-scan base-package="com.gongsi.controller"></context:component-scan>
      <!--  视图解析器:通用的 -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/jsp/"></property> 
            <property name="suffix" value=".jsp"></property>     
      </bean>
      <!-- 映射器 -->
      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
      <!-- 适配器 -->
      <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
               <!-- 整合json使用配置 -->
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
      </bean>
 
</beans>

7、自定义注解目录


8、DataSource.java

package com.gongsi.util;


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


import java.lang.annotation.ElementType;


/*@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSource {  
    String value();  
}  

9、DataSourceAspect.java

package com.gongsi.util;
import java.lang.reflect.Method;  


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
  
public class DataSourceAspect {


    /**
     * 拦截目标方法,获取由@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());
        }
    }


}

10、DynamicDataSource.java

package com.gongsi.util;


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


public class DynamicDataSource extends AbstractRoutingDataSource {


    @Override
    protected Object determineCurrentLookupKey() {
        // 从自定义的位置获取数据源标识
        return DynamicDataSourceHolder.getDataSource();
    }


}

11、DynamicDataSourceHolder.java

package com.gongsi.util;


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


import java.lang.annotation.ElementType;


public class DynamicDataSourceHolder {
    /**
     * 注意:数据源标识保存在线程变量中,避免多线程操作数据源时互相干扰
     */
    private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();


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


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


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


}

12、使用注解

13、注解的具体使用

里面的value值是在这个文件里面定义的,分离数据库的key

14、本人项目正在使用,所以童叟无欺。附下载地址:http://download.youkuaiyun.com/download/qq_38063475/10170674

,可加群321964905

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值