Spring 事务的坑

直接上代码:

@Service
@Slf4j
public class FinanceWithDrawRecordServiceImpl extends BaseServiceImpl<FinanceWithdrawRecord> implements FinanceWithDrawRecordService {
    
    @Transactional
    public BaseResponse<Void> autoWithdraw(Long bigLogId) {
           //.....省略一大片代码

           this.createAccountingReceivableItem(financeBidLog.getOrderId());
   
    }

    @Transactional
    private void createAccountingReceivableItem(Long orderId){
        try {
           
                //生成台账
                accountingReceivableItemService.createAccountingReceivableItem(financePayment);
            }
        } catch (Exception ex){
            log.error("订单id{}提现生成台账失败,", orderId, ex);
        }
    }
}

@Service
public class AccountingReceivableItemServiceImpl extends BaseServiceImpl<AccountingReceivableItem>
        implements AccountingReceivableItemService {

    @Transactional
    public BaseResponse<Void> createAccountingReceivableItem(FinancePayment payment) {
        throw new FinanceException("ex");

    }
}

几个坑:

  1. 通过 this 调用当前类方法,被调用的方法本身没事务,只有调用方本身有事务。所以需要 try catch 代码块处理异常,不影响被调用方的事务。

  2. 示例依然会抛异常回滚。因为 AccountingReceivableItemServiceImpl 的 createAccountingReceivableItem 方法是由 Spring Bean 管理的,这里 FinanceWithDrawRecordServiceImpl 调用 accountingReceivableItemService.createAccountingReceivableItem 方法,虽然由 try - catch 代码块抱住,但是 Spring 还是会抛出一个 UnexpectedRollbackException ;

下面看下 Spring 的源码:

    protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
            throws Throwable {

        // If the transaction attribute is null, the method is non-transactional.
        final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
        final PlatformTransactionManager tm = determineTransactionManager(txAttr);
        final String joinpointIdentification = methodIdentification(method, targetClass);

        if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
            // Standard transaction demarcation with getTransaction and commit/rollback calls.
            TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
            Object retVal = null;
            try {
                // This is an around advice: Invoke the next interceptor in the chain.
                // This will normally result in a target object being invoked.
                retVal = invocation.proceedWithInvocation();
            }
            catch (Throwable ex) {
                // target invocation exception
                completeTransactionAfterThrowing(txInfo, ex);
                throw ex;
            }
            finally {
                cleanupTransactionInfo(txInfo);
            }
            commitTransactionAfterReturning(txInfo);
            return retVal;
        }

        
    }

可以看到 Spring 的事务切面在原来的代码外面包了层 try-catch 代码块,在 completeTransactionAfterThrowing 方法里面先抛出了一个 UnexpectedRollbackException ,在把原异常对象 ex 抛出。所以总的事务还是回滚了。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,434评论 19赞 139
  • 很多人喜欢这篇文章,特此同步过来 由浅入深谈论spring事务 前言 这篇其实也要归纳到《常识》系列中,但这重点又...
    码农戏码阅读 5,007评论 2赞 59
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 35,491评论 18赞 399
  • 童年是愉快的 童年是在裤子 快要掉下来的时候 忘乎所以的玩耍 然后就过了, 那短发 那小腿 摸沙的少年便已成长, ...
    赵林雨轩阅读 191评论 0赞 1
  • 1.二战考上研究生 2.托业或事业单位 3.一分朝九晚六的工作 4.带爸爸体检 5.用自己的薪水给家人买礼物 6....
    一只废柴羊啊阅读 287评论 0赞 0

友情链接更多精彩内容