TransactionSynchronization的invokeAfterCompletion事务源码解析

 更新时间:2023年09月11日 11:04:22   作者:codecraft  
这篇文章主要为大家介绍了TransactionSynchronization的invokeAfterCompletion事务源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下TransactionSynchronization的invokeAfterCompletion

afterCompletion

org/springframework/transaction/support/TransactionSynchronization.java

public interface TransactionSynchronization extends Flushable {
    /** Completion status in case of proper commit. */
    int STATUS_COMMITTED = 0;
    /** Completion status in case of proper rollback. */
    int STATUS_ROLLED_BACK = 1;
    /** Completion status in case of heuristic mixed completion or system errors. */
    int STATUS_UNKNOWN = 2;
    //......
    /**
     * Invoked after transaction commit. Can perform further operations right
     * <i>after</i> the main transaction has <i>successfully</i> committed.
     * <p>Can e.g. commit further operations that are supposed to follow on a successful
     * commit of the main transaction, like confirmation messages or emails.
     * <p><b>NOTE:</b> The transaction will have been committed already, but the
     * transactional resources might still be active and accessible. As a consequence,
     * any data access code triggered at this point will still "participate" in the
     * original transaction, allowing to perform some cleanup (with no commit following
     * anymore!), unless it explicitly declares that it needs to run in a separate
     * transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} for any
     * transactional operation that is called from here.</b>
     * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b>
     * (note: do not throw TransactionException subclasses here!)
     */
    default void afterCommit() {
    }
    /**
     * Invoked after transaction commit/rollback.
     * Can perform resource cleanup <i>after</i> transaction completion.
     * <p><b>NOTE:</b> The transaction will have been committed or rolled back already,
     * but the transactional resources might still be active and accessible. As a
     * consequence, any data access code triggered at this point will still "participate"
     * in the original transaction, allowing to perform some cleanup (with no commit
     * following anymore!), unless it explicitly declares that it needs to run in a
     * separate transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW}
     * for any transactional operation that is called from here.</b>
     * @param status completion status according to the {@code STATUS_*} constants
     * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b>
     * (note: do not throw TransactionException subclasses here!)
     * @see #STATUS_COMMITTED
     * @see #STATUS_ROLLED_BACK
     * @see #STATUS_UNKNOWN
     * @see #beforeCompletion
     */
    default void afterCompletion(int status) {
    }
}
afterCompletion方法有入参status,表示事务结束时候的状态,0表示事务已提交,1表示事务已回滚,2表示事务未知;与afterCommit的一个最重要的区别是afterCompletion的异常会被捕获,不像afterCommit会抛给调用方

invokeAfterCompletion

org/springframework/transaction/support/TransactionSynchronizationUtils.java

/**
     * Actually invoke the {@code afterCompletion} methods of the
     * given Spring TransactionSynchronization objects.
     * @param synchronizations a List of TransactionSynchronization objects
     * @param completionStatus the completion status according to the
     * constants in the TransactionSynchronization interface
     * @see TransactionSynchronization#afterCompletion(int)
     * @see TransactionSynchronization#STATUS_COMMITTED
     * @see TransactionSynchronization#STATUS_ROLLED_BACK
     * @see TransactionSynchronization#STATUS_UNKNOWN
     */
    public static void invokeAfterCompletion(@Nullable List<TransactionSynchronization> synchronizations,
            int completionStatus) {
        if (synchronizations != null) {
            for (TransactionSynchronization synchronization : synchronizations) {
                try {
                    synchronization.afterCompletion(completionStatus);
                }
                catch (Throwable tsex) {
                    logger.error("TransactionSynchronization.afterCompletion threw exception", tsex);
                }
            }
        }
    }
可以看到TransactionSynchronizationUtils的invokeAfterCompletion方法会遍历synchronizations,挨个执行afterCompletion,注意这里catch了Throwable异常,进行了error级别的log

AbstractPlatformTransactionManager

org/springframework/transaction/support/AbstractPlatformTransactionManager.java

/**
     * Actually invoke the {@code afterCompletion} methods of the
     * given Spring TransactionSynchronization objects.
     * <p>To be called by this abstract manager itself, or by special implementations
     * of the {@code registerAfterCompletionWithExistingTransaction} callback.
     * @param synchronizations a List of TransactionSynchronization objects
     * @param completionStatus the completion status according to the
     * constants in the TransactionSynchronization interface
     * @see #registerAfterCompletionWithExistingTransaction(Object, java.util.List)
     * @see TransactionSynchronization#STATUS_COMMITTED
     * @see TransactionSynchronization#STATUS_ROLLED_BACK
     * @see TransactionSynchronization#STATUS_UNKNOWN
     */
    protected final void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) {
        TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
    }
    /**
     * Trigger {@code afterCompletion} callbacks.
     * @param status object representing the transaction
     * @param completionStatus completion status according to TransactionSynchronization constants
     */
    private void triggerAfterCompletion(DefaultTransactionStatus status, int completionStatus) {
        if (status.isNewSynchronization()) {
            List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
            TransactionSynchronizationManager.clearSynchronization();
            if (!status.hasTransaction() || status.isNewTransaction()) {
                if (status.isDebug()) {
                    logger.trace("Triggering afterCompletion synchronization");
                }
                // No transaction or new transaction for the current scope ->
                // invoke the afterCompletion callbacks immediately
                invokeAfterCompletion(synchronizations, completionStatus);
            }
            else if (!synchronizations.isEmpty()) {
                // Existing transaction that we participate in, controlled outside
                // of the scope of this Spring transaction manager -> try to register
                // an afterCompletion callback with the existing (JTA) transaction.
                registerAfterCompletionWithExistingTransaction(status.getTransaction(), synchronizations);
            }
        }
    }
AbstractPlatformTransactionManager的invokeAfterCompletion委托给了TransactionSynchronizationUtils.invokeAfterCompletion;triggerAfterCompletion主要是根据事务状态执行不同逻辑,分别是invokeAfterCompletion与registerAfterCompletionWithExistingTransaction,后者主要是JTA之类的场景,它回传的status是STATUS_UNKNOWN

小结

afterCompletion方法有入参status,表示事务结束时候的状态,0表示事务已提交,1表示事务已回滚,2表示事务未知(一般是JTA相关);与afterCommit的一个最重要的区别是afterCompletion的异常(Throwable)会被捕获,不像afterCommit会抛给调用方

doc 聊聊spring的TransactionSynchronizationAdapter

以上就是TransactionSynchronization的invokeAfterCompletion事务源码解析的详细内容,更多关于TransactionSynchronization invokeAfterCompletion的资料请关注脚本之家其它相关文章!

相关文章

  • Java+LibreOffice实现Excel转PDF并横向一页显示所有列

    Java+LibreOffice实现Excel转PDF并横向一页显示所有列

    在实际业务场景中,用户往往会提供格式不一的 Excel 文件,有时希望将其转换为 PDF 并横向显示,所有列压缩在一页内,下面我们来看看具体实现方法吧
    2025-06-06
  • springboot+mybatis如何屏蔽掉mybatis日志

    springboot+mybatis如何屏蔽掉mybatis日志

    这篇文章主要介绍了springboot+mybatis如何屏蔽掉mybatis日志问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • 从入门到精通详解Java Apache POI操作Excel的实战教程

    从入门到精通详解Java Apache POI操作Excel的实战教程

    在Java开发中,Excel文件处理是一项常见且重要的技能,Apache POI作为Java操作Excel的经典库,提供了强大的API支持,本文从基础IO流操作Excel的局限性入手,本文详细介绍了Apache POI的核心概念,依赖配置,以及实战案例
    2026-05-05
  • Java面试题冲刺第十六天--消息队列

    Java面试题冲刺第十六天--消息队列

    这篇文章主要为大家分享了最有价值的三道关于消息队列的面试题,涵盖内容全面,包括数据结构和算法相关的题目、经典面试编程题等,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • pagehelper分页工具类的封装

    pagehelper分页工具类的封装

    这篇文章主要为大家详细介绍了pagehelper分页工具类的封装,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • Spring JDBC的使用详解

    Spring JDBC的使用详解

    这篇文章主要介绍了Spring JDBC的使用详解,帮助大家更好的理解和学习使用SpringBoot框架,感兴趣的朋友可以了解下
    2021-05-05
  • Java中的值传递和引用传递区别解析

    Java中的值传递和引用传递区别解析

    这篇文章主要介绍了Java中的值传递和引用传递区别解析,引用类型的变量保存引用值,“引用值”指向内存空间的地址,代表了某个对象的引用,而不是对象本身,对象本身存放在该引用值所表示的地址的位置,包含:数组、类、接口,需要的朋友可以参考下
    2023-11-11
  • Java接口回调的本质详解

    Java接口回调的本质详解

    大家好,本篇文章主要讲的是Java接口回调的本质详解,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-02-02
  • Java中单例模式详解

    Java中单例模式详解

    这篇文章主要介绍了Java中单例模式详解,单例模式包括了懒汉式单例、饿汉式单例、登记式单例三种,想要了解的朋友可以了解一下。
    2016-11-11
  • 关于spring依赖注入的方式以及优缺点

    关于spring依赖注入的方式以及优缺点

    这篇文章主要介绍了关于spring依赖注入的方式以及优缺点,依赖注入,是IOC的一个方面,是个通常的概念,它有多种解释,这概念是说你不用创建对象,而只需要描述它如何被创建,需要的朋友可以参考下
    2023-07-07

最新评论