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");
}
}
}