一、总结

1. 动态代理

由cglib或jdk动态代理生成代理类

点击查看代码
//代理对象:
//org.springframework.jdbc.datasource.DataSourceTransactionManager
//开启事务
target.invoke1(){
    insertMethod1()
    insertMethod2()
    updateMethod1()
}
//事务提交

事务操作必须使用同一个connection对象,如何保证
spring每次操作db的时候都需要获取一个connection连接,每次连接都放在ThreadLocal中。

点击查看代码
DataSourceTransactionManager类doGetTransaction
protected Object doGetTransaction() {
    DataSourceTransactionManager.DataSourceTransactionObject txObject = new DataSourceTransactionManager.DataSourceTransactionObject();
    txObject.setSavepointAllowed(this.isNestedTransactionAllowed());
    //这里是到TransactionSynchronizationManager里获取threadLocal线程绑定的连接
    ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(this.obtainDataSource());
    txObject.setConnectionHolder(conHolder, false);
    return txObject;
}

2. Transactional原理

点击查看代码
1.引入数据源、数据库驱动、Spring-jdbc模块
2.事务操作加上@Transactional
3.打开事务功能 @EnableTransactionManagement 
4.EnableTransactionManagement引入了一个ImportSelector
5.selector往spring容器中注册了两个组件:AutoProxyRegistrar和ProxyTransactionManagementConfiguration
5.1.AutoProxyRegistrar主要利用ImporyBeanDefinitionRegistrar注册了一个InfrastructureAdvisorAutoProxyCreator组件
 InfrastructureAdvisorAutoProxyCreator实现了spring后置处理器接口,让需要进行事务处理的方法具备事务的能力(即向spring容器中添加了5.2里的BeanFactoryTransactionAttributeSourceAdvisor,进行了增强)
5.2 ProxyTransactionManagementConfiguration向容器中注册了两个bean:AnnotationTransactionAttributeSource和TransactionInterceptor放到BeanFactoryTransactionAttributeSourceAdvisor中
5.2.1 AnnotationTransactionAttributeSource 的作用是解析业务代码中@Transactional注解的元信息,传播属性,超时时间,隔离级别
5.2.2 TransactionInterceptor保存了事务属性信息以及事务管理器;它是一个MethodInterceptor;
6.当业务代码执行时,由注册的拦截器TransactionInterceptor进行执行invoke方法
7.TransactionAspectSupport类下的invokeWithinTransaction方法是具体的实现

二、Transactional具体实现原理

1.使用注解@Transactional

点击查看代码
//第一步:导入相关数据库依赖;
//第二步:加事务注解;
@Transactional(rollbackFor = {Exception.class})
public void updateAccount(int id) {
    int rows = accounMapper.deduction(id);
    if (rows > 0) {
        System.out.println("秒杀库存修改成功");
        insertGoodOrder();
    } else {
        System.out.println("秒杀修改失败");
    }
}

2.开启事务管理器并注册事务管理器

点击查看代码
 
@Configuration
@ComponentScan("top.yonyong.db")
//第三步:开启事务管理功能,让@Transactional生效
@EnableTransactionManagement 
public class DataSourceConfig {
 
 
    //创建数据源 这个c3p0封装了JDBC, dataSource 接口的实现
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql//localhost:3306/order");
        return dataSource;
    }
 
    @Bean //第四步:注册事务管理器bean
    public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException {
        return new DataSourceTransactionManager(dataSource());
    }
 
    @Bean //第五步:jdbcTemplate能简化增查改删的操作
    public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
        return new JdbcTemplate(dataSource());
    }
}

3. 赋予代码事务能力

点击查看代码
package org.springframework.transaction.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Import;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//利用Import给容器添加一个Selector组件;
@Import({TransactionManagementConfigurationSelector.class})
public @interface EnableTransactionManagement {
    //使用JDK或者是Cglib动态代理
    //true:Ciglib动态代理 false JDK动态代理,默认false
    boolean proxyTargetClass() default false;

    //默认事务增强器是什么模式:代理
    AdviceMode mode() default AdviceMode.PROXY;

    //最低的优先级
    int order() default 2147483647;
}

4. @Import和[@ImportSelector + @ImportBeanDefinitionRegistor ]

spring源码里常出现这两个注解:
ImportSelector是一个接口,只需要实现selectImport()方法,返回的是一个数组,即可给容器批量的注册Bean实例;
ImportBeanDefinitionRegistor也是一个接口,只需要实现registorBeanDefinition()方法就能实现给容器添加bean实例;

点击查看代码
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {

   /**
    * TransactionManagementConfigurationSelector 实现了AdviceModeImportSelector
    * 而AdviceModeImportSelector实现了ImportSelector ,所以也就拥有了向spring容器注册bean的能力
    */
   @Override
   protected String[] selectImports(AdviceMode adviceMode) {
      switch (adviceMode) {
         case PROXY:
             //默认代理模式
             //注册AutoProxyRegistrar和ProxyTransactionManagementConfiguration两个类
            return new String[] {AutoProxyRegistrar.class.getName(),
                  ProxyTransactionManagementConfiguration.class.getName()};
         case ASPECTJ:
            return new String[] {determineTransactionAspectClass()};
         default:
            return null;
      }
   }

   private String determineTransactionAspectClass() {
      return (ClassUtils.isPresent("javax.transaction.Transactional", getClass().getClassLoader()) ?
            TransactionManagementConfigUtils.JTA_TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME :
            TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME);
   }

}

4.1 AutoProxyRegistrar类

通过ImportBeanDefinitionRegistrar给容器中添加组件:InfrastructureAdvisorAutoProxyCreator

点击查看代码
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
 
   private final Log logger = LogFactory.getLog(getClass());
 
   @Override
   public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
      boolean candidateFound = false;
      Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
      for (String annoType : annoTypes) {
 
         if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
               Boolean.class == proxyTargetClass.getClass()) {
            candidateFound = true;
            if (mode == AdviceMode.PROXY) {//看它给容器中注册了什么组件
               AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
               if ((Boolean) proxyTargetClass) {
                  AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
                  return;
               }
            }
}
 
@Nullable //给容器中添加InfrastructureAdvisorAutoProxyCreator组件
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry,Object source) {
        //这里开始给容器注册:InfrastructureAdvisorAutoProxyCreator 事务动态代理创建器组件
   return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}

一直点进去发现,InfrastructureAdvisorAutoProxyCreator其实实现了spring后置处理器,用来创建增强的bean

点击查看代码
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
    public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
        public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
                      implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {}
 
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
    public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
        @Nullable  //Bean实例前置增强
        default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
           return bean;
        }
 
        @Nullable //Bean实例后置增强
        default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
           return bean;
        }
}

4.2 ProxyTransactionManagementConfiguration类

点击查看代码
@Configuration(proxyBeanMethods = false)
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

    //开始事务的元数据属性解析
   @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   
   //对属性元信息的一些增强,比如在注解中设置的一些参数:传播属性propagation,回滚的条件rollbackFor等等
   //@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
   public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
         TransactionAttributeSource transactionAttributeSource,
         TransactionInterceptor transactionInterceptor) {
      //对我们的事务进行属性增强;
      BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
      advisor.setTransactionAttributeSource(transactionAttributeSource);
      advisor.setAdvice(transactionInterceptor);
      if (this.enableTx != null) {
         advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
      }
      return advisor;
   }

    //封装事务的属性值,注册为bean,作为形参供上面的方法使用
   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionAttributeSource transactionAttributeSource() {
       //新建了这个对象
      return new AnnotationTransactionAttributeSource();
   }

    //主要用于保存事务配置属性的信息,封装成一个TransactionInterceptor
   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionInterceptor transactionInterceptor(
         TransactionAttributeSource transactionAttributeSource) {
      TransactionInterceptor interceptor = new TransactionInterceptor();
      interceptor.setTransactionAttributeSource(transactionAttributeSource);
      if (this.txManager != null) {
         interceptor.setTransactionManager(this.txManager);
      }
      return interceptor;
   }

}
点击查看代码
public class AnnotationTransactionAttributeSource extends AbstractFallbackTransactionAttributeSource
      implements Serializable {
        
    public AnnotationTransactionAttributeSource() {
       this(true);
    }  
    
    //花里胡哨不知道干啥的,但最终都会加上一个SpringTransactionAnnotationParser
    public AnnotationTransactionAttributeSource(boolean publicMethodsOnly) {
       this.publicMethodsOnly = publicMethodsOnly;
       if (jta12Present || ejb3Present) {
          this.annotationParsers = new LinkedHashSet<>(4);
          this.annotationParsers.add(new SpringTransactionAnnotationParser());
          if (jta12Present) {
             this.annotationParsers.add(new JtaTransactionAnnotationParser());
          }
          if (ejb3Present) {
             this.annotationParsers.add(new Ejb3TransactionAnnotationParser());
          }
       }
       else {
          this.annotationParsers = Collections.singleton(new SpringTransactionAnnotationParser());
       }
    }
}


public class SpringTransactionAnnotationParser implements TransactionAnnotationParser, Serializable {

   @Override
   public boolean isCandidateClass(Class<?> targetClass) {
      return AnnotationUtils.isCandidateClass(targetClass, Transactional.class);
   }

   @Override
   @Nullable
   public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
      AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
            element, Transactional.class, false, false);
      if (attributes != null) {
         return parseTransactionAnnotation(attributes);
      }
      else {
         return null;
      }
   }

   public TransactionAttribute parseTransactionAnnotation(Transactional ann) {
      return parseTransactionAnnotation(AnnotationUtils.getAnnotationAttributes(ann, false, false));
   }

   protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
      RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();

      //事务传播属性的设置
      Propagation propagation = attributes.getEnum("propagation");
      rbta.setPropagationBehavior(propagation.value());
      //事务的隔离属性的设置
      Isolation isolation = attributes.getEnum("isolation");
      rbta.setIsolationLevel(isolation.value());
      //事务的超时时间设置
      rbta.setTimeout(attributes.getNumber("timeout").intValue());
      rbta.setReadOnly(attributes.getBoolean("readOnly"));
      rbta.setQualifier(attributes.getString("value"));

      //事务的回滚条件设置
      List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
      for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
         rollbackRules.add(new RollbackRuleAttribute(rbRule));
      }
      //设置需要进行回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,则进行事务回滚
      for (String rbRule : attributes.getStringArray("rollbackForClassName")) {
         rollbackRules.add(new RollbackRuleAttribute(rbRule));
      }
      for (Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
         rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
      }
      //设置不回滚的异常类名称数组,当方法中抛出指定异常名称数组中的异常时,事务不回滚
      for (String rbRule : attributes.getStringArray("noRollbackForClassName")) {
         rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
      }
      rbta.setRollbackRules(rollbackRules);

      return rbta;
   }


   @Override
   public boolean equals(@Nullable Object other) {
      return (this == other || other instanceof SpringTransactionAnnotationParser);
   }

   @Override
   public int hashCode() {
      return SpringTransactionAnnotationParser.class.hashCode();
   }

}

到这里:第一就阶段的初始化任务就完成了,核心任务:

利用TransactionManagementConfigurationSelector给容器中导入两个组件:
(1)InfrastructureAdvisorAutoProxyCreator
AutoProxyRegistrar给容器中注册一个 InfrastructureAdvisorAutoProxyCreator组件,它其实就是一个后置处理器,一个动态代理创建器,利用后置处理器和动态代理对目标方法进行增强,>返回一个增强的实例对象,代理对象执行方法利用拦截器链进行调用;
(2)ProxyTransactionManagementConfiguration
对事务管理器的获取,对事务的元信息进行处理,对目标方法本身的执行,主要是事务能力细节的代理实现,然后给容器中注册配置生成的事务增强器Bean;

5.调用执行

目标方法的调用,开始调用TransactionInterceptor.invoke() 方法,这个是事务执行的核心

5.1 TransactionInterceptor 类

点击查看代码
//这里拦截后封装成 MethodInterceptor,保存了事务的信息,和aop的逻辑一样
public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor, Serializable {

   public TransactionInterceptor() {
   }
   
   public TransactionInterceptor(PlatformTransactionManager ptm, Properties attributes) {
      setTransactionManager(ptm);
      setTransactionAttributes(attributes);
   }
   
   public TransactionInterceptor(PlatformTransactionManager ptm, TransactionAttributeSource tas) {
      setTransactionManager(ptm);
      setTransactionAttributeSource(tas);
   }


   //动态代理的调用
   @Override
   @Nullable
   public Object invoke(MethodInvocation invocation) throws Throwable {
      Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

      // Adapt to TransactionAspectSupport's invokeWithinTransaction...
      //这里调用的是TransactionAspectSupport类的方法
      return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
   }


   //---------------------------------------------------------------------
   // Serialization support
   //---------------------------------------------------------------------

   private void writeObject(ObjectOutputStream oos) throws IOException {
      // Rely on default serialization, although this class itself doesn't carry state anyway...
      oos.defaultWriteObject();

      // Deserialize superclass fields.
      oos.writeObject(getTransactionManagerBeanName());
      oos.writeObject(getTransactionManager());
      oos.writeObject(getTransactionAttributeSource());
      oos.writeObject(getBeanFactory());
   }

   private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
      ois.defaultReadObject();

      setTransactionManagerBeanName((String) ois.readObject());
      setTransactionManager((PlatformTransactionManager) ois.readObject());
      setTransactionAttributeSource((TransactionAttributeSource) ois.readObject());
      setBeanFactory((BeanFactory) ois.readObject());
   }

}

5.2 TransactionAspectSupport类

点击查看代码
//TransactionAspectSupport类 invokeWithinTransaction方法
@Nullable
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
      final InvocationCallback invocation) throws Throwable {

   // If the transaction attribute is null, the method is non-transactional.
    //(1):获取(实践第二步中)设置的事务属性信息(propagation = Propagation.REQUIRED, rollbackFor = Exception.class),直接从内存中加载;
   TransactionAttributeSource tas = getTransactionAttributeSource();
   final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
   //(2):获取注册的事务管理器-PlatformTransactionManager,加载到容器中;
   final TransactionManager tm = determineTransactionManager(txAttr);

   if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
      ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
         if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) {
            throw new TransactionUsageException(
                  "Unsupported annotated transaction on suspending function detected: " + method +
                  ". Use TransactionalOperator.transactional extensions instead.");
         }
         ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType());
         if (adapter == null) {
            throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
                  method.getReturnType());
         }
         return new ReactiveTransactionSupport(adapter);
      });
      return txSupport.invokeWithinTransaction(
            method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm);
   }

   PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
   final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

   if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
      // Standard transaction demarcation with getTransaction and commit/rollback calls.
      //得到事务管理器,关闭事务自动提交;
      TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);

      Object retVal;
      try {
         // This is an around advice: Invoke the next interceptor in the chain.
         // This will normally result in a target object being invoked.
         //(4): 开始执行目标方法本身doBusiness();
         retVal = invocation.proceedWithInvocation();
      }
      catch (Throwable ex) {
         // target invocation exception
         //(4.1): 如果执行过程中抛出异常则回滚
         completeTransactionAfterThrowing(txInfo, ex);
         throw ex;
      }
      finally {
         cleanupTransactionInfo(txInfo);
      }

      if (vavrPresent && VavrDelegate.isVavrTry(retVal)) {
         // Set rollback-only in case of Vavr failure matching our rollback rules...
         TransactionStatus status = txInfo.getTransactionStatus();
         if (status != null && txAttr != null) {
            retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
         }
      }
      //(4.2) 如果执行成功,则提交事务;
      commitTransactionAfterReturning(txInfo);
      return retVal;
   }

   else {
      final ThrowableHolder throwableHolder = new ThrowableHolder();

      // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
      try {
         Object result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
            TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
            try {
               Object retVal = invocation.proceedWithInvocation();
               if (vavrPresent && VavrDelegate.isVavrTry(retVal)) {
                  // Set rollback-only in case of Vavr failure matching our rollback rules...
                  retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
               }
               return retVal;
            }
            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.
                  throwableHolder.throwable = ex;
                  return null;
               }
            }
            finally {
               cleanupTransactionInfo(txInfo);
            }
         });

         // Check result state: It might indicate a Throwable to rethrow.
         if (throwableHolder.throwable != null) {
            throw throwableHolder.throwable;
         }
         return result;
      }
      catch (ThrowableHolderException ex) {
         throw ex.getCause();
      }
      catch (TransactionSystemException ex2) {
         if (throwableHolder.throwable != null) {
            logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
            ex2.initApplicationException(throwableHolder.throwable);
         }
         throw ex2;
      }
      catch (Throwable ex2) {
         if (throwableHolder.throwable != null) {
            logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
         }
         throw ex2;
      }
   }
}

5.3 初始化datasource时注册的事务管理器

点击查看代码
public class DataSourceTransactionManager extends AbstractPlatformTransactionManager  
        implements ResourceTransactionManager, InitializingBean {  
    //注入数据源  
    private DataSource dataSource;  
//数据源事务处理器默认构造方法,创建一个数据源事务处理器实例,并设置允许嵌套事务  
    public DataSourceTransactionManager() {  
        setNestedTransactionAllowed(true);  
    }  
    //根据给定数据源,创建一个数据源事务处理器实例  
    public DataSourceTransactionManager(DataSource dataSource) {  
        this();  
        setDataSource(dataSource);  
        afterPropertiesSet();  
    }  
    //设置数据源  
    public void setDataSource(DataSource dataSource) {  
        if (dataSource instanceof TransactionAwareDataSourceProxy) {  
            //如果数据源是一个事务包装数据源代理,则获取事务包装代理的目标数据源   
            this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();  
        }  
        else {  
            this.dataSource = dataSource;  
        }  
    }  
    //获取数据源  
    public DataSource getDataSource() {  
        return this.dataSource;  
    }  
    //数据源事务处理器对象构造方法的回调函数  
    public void afterPropertiesSet() {  
        if (getDataSource() == null) {  
            throw new IllegalArgumentException("Property 'dataSource' is required");  
        }  
    }  
    public Object getResourceFactory() {  
        return getDataSource();  
    }  
//创建事务,对数据库而言,是由Connection来完成事务工作的。该方法把数据库的//Connection对象放到一个ConnectionHolder对象中,然后封装到一个  
//DataSourceTransactionObject对象中  
    protected Object doGetTransaction() {  
        //创建数据源事务对象  
        DataSourceTransactionObject txObject = new DataSourceTransactionObject();  
        //设置数据源事务对象对嵌套事务使用保存点  
        txObject.setSavepointAllowed(isNestedTransactionAllowed());  
        //从事务管理容器中获取存放数据库Connection的对象  
        ConnectionHolder conHolder =  
            (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);  
        txObject.setConnectionHolder(conHolder, false);  
        return txObject;  
    }  
    //判断是否已经存在事务  
    protected boolean isExistingTransaction(Object transaction) {  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;  
    //根据存放数据库连接的ConnectionHolder的isTransactionActive属性来判断  
        return (txObject.getConnectionHolder() != null && txObject.getConnectionHolder().isTransactionActive());  
    }  
    //处理事务开始的方法  
    protected void doBegin(Object transaction, TransactionDefinition definition) {  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;  
        Connection con = null;  
        try {  
            //如果数据源事务对象的ConnectionHolder为null或者是事务同步的  
            if (txObject.getConnectionHolder() == null ||  
        txObject.getConnectionHolder().isSynchronizedWithTransaction()) {  
                //获取当前数据源的数据库连接  
                Connection newCon = this.dataSource.getConnection();  
                if (logger.isDebugEnabled()) {  
                    logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");  
                }  
                //为数据源事务对象设置ConnectionHolder  
                txObject.setConnectionHolder(new ConnectionHolder(newCon), true);  
            }  
    //设置数据源事务对象的事务同步    txObject.getConnectionHolder().setSynchronizedWithTransaction(true);  
            //获取数据源事务对象的数据库连接  
            con = txObject.getConnectionHolder().getConnection();  
            //根据数据连接和事务属性,获取数据库连接的事务隔离级别  
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);  
    //为数据源事务对象设置事务隔离级别  
    txObject.setPreviousIsolationLevel(previousIsolationLevel);  
            //如果数据库连接设置了自动事务提交属性,则关闭自动提交  
            if (con.getAutoCommit()) {  
                //保存数据库连接设置的自动连接到数据源事务对象中  
                txObject.setMustRestoreAutoCommit(true);  
                if (logger.isDebugEnabled()) {  
                    logger.debug("Switching JDBC Connection [" + con + "] to manual commit");  
                }  
                //设置数据库连接自动事务提交属性为false,即禁止自动事务提交  
                con.setAutoCommit(false);  
            }  
            //激活当前数据源事务对象的事务配置  
            txObject.getConnectionHolder().setTransactionActive(true);  
            //获取事务配置的超时时长  
int timeout = determineTimeout(definition);  
//如果事务配置的超时时长不等于事务的默认超时时长  
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {  
        //数据源事务对象设置超时时长  
        txObject.getConnectionHolder().setTimeoutInSeconds(timeout);  
            }  
            //把当前数据库Connection和线程绑定  
            if (txObject.isNewConnectionHolder()) {  
        TransactionSynchronizationManager.bindResource(getDataSource(), txObject.getConnectionHolder());  
            }  
        }  
        catch (Exception ex) {  
            DataSourceUtils.releaseConnection(con, this.dataSource);  
            throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);  
        }  
    }  
    //事务挂起  
    protected Object doSuspend(Object transaction) {  
        //获取事务对象  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;  
        //将事务对象中的ConnectionHolders设置为null  
        txObject.setConnectionHolder(null);  
        ConnectionHolder conHolder = (ConnectionHolder)  
        //解除事务对象和当前线程的绑定    TransactionSynchronizationManager.unbindResource(this.dataSource);  
        return conHolder;  
    }  
    //事务恢复  
    protected void doResume(Object transaction, Object suspendedResources) {  
        //获取已暂停事务的ConnectionHolder  
        ConnectionHolder conHolder = (ConnectionHolder) suspendedResources;  
        //重新将事务对象和当前线程绑定  
        TransactionSynchronizationManager.bindResource(this.dataSource, conHolder);  
    }  
    //事务提交  
    protected void doCommit(DefaultTransactionStatus status) {  
        //获取事务对象  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();  
        //通过事务对象获取数据库连接  
        Connection con = txObject.getConnectionHolder().getConnection();  
        if (status.isDebug()) {  
            logger.debug("Committing JDBC transaction on Connection [" + con + "]");  
        }  
        try {  
            //使用数据库连接手动进行事务提交  
            con.commit();  
        }  
        catch (SQLException ex) {  
            throw new TransactionSystemException("Could not commit JDBC transaction", ex);  
        }  
    }  
    //事务回滚  
    protected void doRollback(DefaultTransactionStatus status) {  
        //获取事务对象  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();  
        //通过事务对象获取数据库连接  
        Connection con = txObject.getConnectionHolder().getConnection();  
        if (status.isDebug()) {  
            logger.debug("Rolling back JDBC transaction on Connection [" + con + "]");  
        }  
        try {  
            //通过调用数据库连接的回滚方法完成事务回滚操作  
            con.rollback();  
        }  
        catch (SQLException ex) {  
            throw new TransactionSystemException("Could not roll back JDBC transaction", ex);  
        }  
    }  
    //设置回滚  
    protected void doSetRollbackOnly(DefaultTransactionStatus status) {  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) status.getTransaction();  
        if (status.isDebug()) {  
            logger.debug("Setting JDBC transaction [" + txObject.getConnectionHolder().getConnection() +  
                    "] rollback-only");  
        }  
        txObject.setRollbackOnly();  
    }  
    //操作完成之后清除操作  
    protected void doCleanupAfterCompletion(Object transaction) {  
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;  
        //移除当前线程绑定的ConnectionHolder  
        if (txObject.isNewConnectionHolder()) {  
    TransactionSynchronizationManager.unbindResource(this.dataSource);  
        }  
        Connection con = txObject.getConnectionHolder().getConnection();  
        try {  
        //如果事务对象保存了自动事务提交属性,则设置数据库连接的自动事务提交属性  
            if (txObject.isMustRestoreAutoCommit()) {  
                con.setAutoCommit(true);  
            }  
            //事务结束后重置数据库连接  
            DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel());  
        }  
        catch (Throwable ex) {  
            logger.debug("Could not reset JDBC Connection after transaction", ex);  
        }  
        //如果事务对象中有新的ConnectionHolder   
        if (txObject.isNewConnectionHolder()) {  
            if (logger.isDebugEnabled()) {  
                logger.debug("Releasing JDBC Connection [" + con + "] after transaction");  
            }  
            //释放数据库连接  
            DataSourceUtils.releaseConnection(con, this.dataSource);  
        }  
        //清除事务对象的ConnectionHolder  
        txObject.getConnectionHolder().clear();  
    }  
//数据源事务对象,内部类  
    private static class DataSourceTransactionObject extends JdbcTransactionObjectSupport {  
        //是否有新的ConnectionHolder  
        private boolean newConnectionHolder;  
        //是否保存自动提交  
        private boolean mustRestoreAutoCommit;  
        //设置ConnectionHolder  
        public void setConnectionHolder(ConnectionHolder connectionHolder, boolean newConnectionHolder) {  
            //为父类JdbcTransactionObjectSupport设置ConnectionHolder  
            super.setConnectionHolder(connectionHolder);  
            this.newConnectionHolder = newConnectionHolder;  
        }  
        public boolean isNewConnectionHolder() {  
            return this.newConnectionHolder;  
        }  
        //调用父类JdbcTransactionObjectSupport的相关方法,查询收费存在事务  
        public boolean hasTransaction() {  
            return (getConnectionHolder() != null && getConnectionHolder().isTransactionActive());  
        }  
        //设置是否保存自动提交  
        public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) {  
            this.mustRestoreAutoCommit = mustRestoreAutoCommit;  
        }  
        public boolean isMustRestoreAutoCommit() {  
            return this.mustRestoreAutoCommit;  
        }  
        //设置数据库连接在操作失败是,是否只回滚处理  
        public void setRollbackOnly() {  
            getConnectionHolder().setRollbackOnly();  
        }  
        public boolean isRollbackOnly() {  
            return getConnectionHolder().isRollbackOnly();  
        }  
    }  
}  


posted on 2021-12-28 02:41  yonyong  阅读(505)  评论(0编辑  收藏  举报