Spring 配置多个数据源

本文介绍如何在Spring框架中配置多个数据源,并通过AOP实现数据源的动态切换。利用自定义的MultipleDataSource类扩展AbstractRoutingDataSource,结合MultiDataSourceInterceptor拦截器,根据不同的业务需求选择合适的数据源。

spring数据源配置多个

<bean id="multipleDataSource" class="bam.datasource.MultipleDataSource">
        <property name="defaultTargetDataSource" ref="oneDataSource"/>
        <property name="targetDataSources">
            <map>
                <entry key="oneDataSource" value-ref="oneDataSource"/>
                <entry key="twoDataSource" value-ref="twoDataSource"/>
            </map>
        </property>
    </bean>

   <!-- 配置sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="multipleDataSource" />
        <property name="mapperLocations" value="classpath:com/mapper/mapping/*.xml" />
    </bean>

类1:设置数据源

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

public class MultipleDataSource extends AbstractRoutingDataSource {

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

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

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

    @Override
    protected Object determineCurrentLookupKey() {
        return dataSourceKey.get();
    }

}

类2:数据源切换

import java.lang.reflect.Method;

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

@Component
@Aspect
@Order(2)
public class MultiDataSourceInterceptor {

    @Before("execution(* com.service.impl..*.*(..))")
    public void switchDs(JoinPoint point) throws Exception {
        final MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        String cname = method.getDeclaringClass().getCanonicalName();
        if (cname.startsWith("One")) {
            MultipleDataSource.setDataSourceKey("oneDataSource");
        } else {
            MultipleDataSource.setDataSourceKey("twoDataSource");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值