spring事物源码分析篇三:业务代码的执行--事物增强器

Posted 烟尘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring事物源码分析篇三:业务代码的执行--事物增强器相关的知识,希望对你有一定的参考价值。

由于springAop的实现思路,在业务代码执行的时候,会将所有的通知转换为拦截器链,所会依次执行拦截器的invoke方法,在spring事物中TransactionInterceptor构成了spring事物的核心。

代码如下:

@Override
    public Object invoke(final MethodInvocation invocation) throws Throwable {
        // Work out the target class: may be {@code null}.
        // The TransactionAttributeSource should be passed the target class
        // as well as the method, which may be from an interface.
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

        // Adapt to TransactionAspectSupport‘s invokeWithinTransaction...
        // 执行业务代码的部分
        return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
            @Override
            public Object proceedWithInvocation() throws Throwable {
               // 执行下一个拦截器
                return invocation.proceed();
            }
        });
    }

进入代码进行分析:

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

        else { 
             //编程式事物处理
            // It‘s a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
            try {
                Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr,
                        new TransactionCallback<Object>() {
                            @Override
                            public Object doInTransaction(TransactionStatus status) {
                                TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
                                try {
                                    return invocation.proceedWithInvocation();
                                }
                                catch (Throwable ex) {
                                    if (txAttr.rollbackOn(ex)) {
                                        // A RuntimeException: will lead to a rollback.
                                        if (ex instanceof RuntimeException) {
                                            throw (RuntimeException) ex;
                                        }
                                        else {
                                            throw new ThrowableHolderException(ex);
                                        }
                                    }
                                    else {
                                        // A normal return value: will lead to a commit.
                                        return new ThrowableHolder(ex);
                                    }
                                }
                                finally {
                                    cleanupTransactionInfo(txInfo);
                                }
                            }
                        });

                // Check result: It might indicate a Throwable to rethrow.
                if (result instanceof ThrowableHolder) {
                    throw ((ThrowableHolder) result).getThrowable();
                }
                else {
                    return result;
                }
            }
            catch (ThrowableHolderException ex) {
                throw ex.getCause();
            }
        }
    }

 

以上是关于spring事物源码分析篇三:业务代码的执行--事物增强器的主要内容,如果未能解决你的问题,请参考以下文章

清晰架构(Clean Architecture)的Go微服务: 事物管理

Spring框架 ? 项目启动时执行特定处理及ApplicationListener源码分析

170110Spring 事物机制总结

Spring源码分析专题 —— 阅读指引

Java小题精炼训练营(篇三)

Spring——事务管理