事务@DS切换多数据源失效 发表于 2026-01-21 | 分类于 ---SpringBoot | 我的代码案例动态数据源 - 文档AOP注解 - 文档 前言 在上面 我的代码案例 已经有了,这里复制一份 12345672026-01-21 15:58:23多数据源,不使用事务问题.问题:在事务中,切换 @DS("doris") 不能切换数据源。说明:我这里的 slave 并不是真正意思的从库,而是大数据的库,如果数据源切换不了,导致查询表不存在了。.解决:AOP 拦截 @DS("doris"),Propagation.NOT_SUPPORTED 不使用事务执行 工具类1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859package com.taopanfeng.springbootdynamicdatasource.aop;import cn.hutool.core.lang.Opt;import com.baomidou.dynamic.datasource.annotation.DS;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.annotation.MergedAnnotations;import org.springframework.stereotype.Component;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.support.TransactionTemplate;import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY;@Aspect@Componentpublic class DorisTransactionAspect { @Autowired private PlatformTransactionManager transactionManager; @Around("execution(* *(..)) && (@within(com.baomidou.dynamic.datasource.annotation.DS) || @annotation(com.baomidou.dynamic.datasource.annotation.DS))") public Object handleDorisTransaction(ProceedingJoinPoint joinPoint) throws Throwable { Class<?> clazz = joinPoint.getTarget().getClass(); DS dsMethod = Opt.ofTry(() -> ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(DS.class)).get(); DS dsClass = Opt.ofTry(() -> clazz.getAnnotation(DS.class)).get(); String dsInterface = Opt.ofTry(() -> MergedAnnotations.from(clazz, TYPE_HIERARCHY).get(DS.class).getString("value")).get(); // 方法 > 类 > 接口 String dataSourceKey = null; if (dsMethod != null) { dataSourceKey = dsMethod.value(); } else if (dsClass != null) { dataSourceKey = dsClass.value(); } else if (dsInterface != null) { dataSourceKey = dsInterface; } // 拦截 @DS("doris") if ("doris".equals(dataSourceKey)) { // 使用编程式事务管理,设置NOT_SUPPORTED传播行为 TransactionTemplate template = new TransactionTemplate(transactionManager); template.setPropagationBehavior(Propagation.NOT_SUPPORTED.value()); return template.execute(status -> { try { return joinPoint.proceed(); } catch (Throwable throwable) { throw new RuntimeException(throwable); } }); } return joinPoint.proceed(); }}