其他分享
首页 > 其他分享> > 14-Spring事务原理

14-Spring事务原理

作者:互联网

  1. @EnableTransactionManagement 利用TransactionManagementConfigurationSelector 往容器中注入了两个类
    AutoProxyRegistrarProxyTransactionManagementConfiguration

  2. AutoProxyRegistrar 往容器中注入了 InfrastructureAdvisorAutoProxyCreator
    InfrastructureAdvisorAutoProxyCreator 也是利用后置处理器机制,在对象创建后,然后包装对象返回一个代理对象
    查看它的父类,发现跟实现AOP的方式是类似的,都是根据一些规则找到对应的增强器,然后封装成MethodInterceptor,当对象调用目标方法时,动态代理机制就会链式调用这些拦截器。

     InfrastructureAdvisorAutoProxyCreator
     extends AbstractAdvisorAutoProxyCreator
         extends AbstractAutoProxyCreator
             extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
    
  3. ProxyTransactionManagementConfiguration类信息如下

@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
    public ProxyTransactionManagementConfiguration() {
    }

    @Bean(
        name = {"org.springframework.transaction.config.internalTransactionAdvisor"}
    )
  	// 给容器中增加了事务增强器
    @Role(2)
    public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
        BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
        advisor.setTransactionAttributeSource(this.transactionAttributeSource());
        advisor.setAdvice(this.transactionInterceptor());
        if (this.enableTx != null) {
            advisor.setOrder((Integer)this.enableTx.getNumber("order"));
        }

        return advisor;
    }

    // 事务注解解析器
    @Bean
    @Role(2)
    public TransactionAttributeSource transactionAttributeSource() {
        return new AnnotationTransactionAttributeSource();
    }

    // 事务拦截器, 它继承了 MethodInterceptor
  	// 因此在收集增强器的时候,这个也会被收集进去
    @Bean
    @Role(2)
    public TransactionInterceptor transactionInterceptor() {
        TransactionInterceptor interceptor = new TransactionInterceptor();
        interceptor.setTransactionAttributeSource(this.transactionAttributeSource());
        if (this.txManager != null) {
            interceptor.setTransactionManager(this.txManager);
        }

        return interceptor;
    }
}

下面主要查看TransactionInterceptor#invoke方法

public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable {
    @Override
    @Nullable
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // 获取目标类
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
        // Adapt to TransactionAspectSupport's invokeWithinTransaction...
        return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
    }
}
public abstract class TransactionAspectSupport implements BeanFactoryAware, InitializingBean {
    @Nullable
    protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
                                             final InvocationCallback invocation) throws Throwable {

        // 1. 获取事务注解解析器
        TransactionAttributeSource tas = getTransactionAttributeSource();
        // 2. 获取事务相关属性
        final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
        // 3. 获取 PlatformTransactionManager
        final PlatformTransactionManager tm = determineTransactionManager(txAttr);
        final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

        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.
                // 4. 这里开始执行目标方法
                retVal = invocation.proceedWithInvocation();
            }
            catch (Throwable ex) {
                // target invocation exception
                // 5. 如果目标方法抛出异常,获取事务管理器,利用事务管理器进行回滚
                completeTransactionAfterThrowing(txInfo, ex);
                throw ex;
            }
            finally {
                cleanupTransactionInfo(txInfo);
            }
            // 6. 如果执行正常,则拿到事务管理器,提交事务
            commitTransactionAfterReturning(txInfo);
            return retVal;
        } else {
            // 省略......
        }
    }
}

标签:事务,14,Spring,targetClass,invocation,interceptor,null,public
来源: https://blog.csdn.net/lizc_lizc/article/details/114234444