spring的事物源码解析

一、注解解析

1
  <tx:annotation-driven></tx:annotation-driven>

TxNamespaceHandler解析XML,AnnotationDrivenBeanDefinitionParser处理相应逻辑;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
  @Override
  public BeanDefinition parse(Element element, ParserContext parserContext) {
      registerTransactionalEventListenerFactory(parserContext);
      String mode = element.getAttribute("mode");
      if ("aspectj".equals(mode)) {
          // mode="aspectj"
          registerTransactionAspect(element, parserContext);
      }
      else {
          // mode="proxy"
          AopAutoProxyConfigurer.configureAutoProxyCreator(element, parserContext);
      }
      return null;
  }

1.AopAutoProxyConfigurer.configureAutoProxyCreator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
          //1.注册InfrastructureAdvisorAutoProxyCreator,支持AOP
          AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);

          String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME;
          if (!parserContext.getRegistry().containsBeanDefinition(txAdvisorBeanName)) {
              Object eleSource = parserContext.extractSource(element);

              // Create the TransactionAttributeSource definition.
              //2.AnnotationTransactionAttributeSource
              RootBeanDefinition sourceDef = new RootBeanDefinition(
                      "org.springframework.transaction.annotation.AnnotationTransactionAttributeSource");
              sourceDef.setSource(eleSource);
              sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
              String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);

              // Create the TransactionInterceptor definition.
              //3.TransactionInterceptor
              RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class);
              interceptorDef.setSource(eleSource);
              interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
              registerTransactionManager(element, interceptorDef);
              interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
              String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);

              // Create the TransactionAttributeSourceAdvisor definition.
              //4.TransactionAttributeSourceAdvisor
              RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class);
              advisorDef.setSource(eleSource);
              advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
              advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
              advisorDef.getPropertyValues().add("adviceBeanName", interceptorName);
              if (element.hasAttribute("order")) {
                  advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
              }
              parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef);

              CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource);
              compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName));
              compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
              compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, txAdvisorBeanName));
              parserContext.registerComponent(compositeDef);
          }
      }

事物支持核心类BeanFactoryTransactionAttributeSourceAdvisor,TransactionAttributeSourcePointcut,TransactionInterceptor,AnnotationTransactionAttributeSource;核心处理TransactionInterceptor;

  • AnnotationTransactionAttributeSource 处理@Transactional注解的属性,map缓存保存RuleBasedTransactionAttribute
  • TransactionAttributeSourcePointcut pointcut
  • TransactionInterceptor Advice
  • BeanFactoryTransactionAttributeSourceAdvisor Advisor

2.TransactionInterceptor invoke

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
   protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
           throws Throwable {
 
       // If the transaction attribute is null, the method is non-transactional.
       //1.获取注解方法上配置RuleBasedTransactionAttribute
       final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
       //2.获取PlatformTransactionManager
       final PlatformTransactionManager tm = determineTransactionManager(txAttr);
       //3.获取事物唯一
       //    先txAttr获取Descriptor
       //    没有在targetClass简名+"."+method名称
       final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
 
       if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
           // Standard transaction demarcation with getTransaction and commit/rollback calls.
           //4.事物开启
           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.
               //5.执行方法
               retVal = invocation.proceedWithInvocation();
           }
           catch (Throwable ex) {
               // target invocation exception
               //6.事物异常
               completeTransactionAfterThrowing(txInfo, ex);
               throw ex;
           }
           finally {
               //7.清理事物信息
               cleanupTransactionInfo(txInfo);
           }
           //8.提交事物
           commitTransactionAfterReturning(txInfo);
           return retVal;
       }
 
       else {
           // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
           //它是一个CallbackPreferringPlatformTransactionManager:传递一个TransactionCallback。
           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();
           }
       }
   }

(1).TransactionAttribute

TransactionDefinition spring事务传播特性和事务的隔离级别定义常量;

事务传播特性:

  • PROPAGATION_REQUIERD:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
  • PROPAGATION_SUPPORTS:支持当前事务,如果没有当前事务,就以非事务方法执行。
  • PROPAGATION_MANDATORY:使用当前事务,如果没有当前事务,就抛出异常。
  • PROPAGATION_REQUIRED_NEW:新建事务,如果当前存在事务,把当前事务挂起。
  • PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
  • PROPAGATION_NEVER:以非事务方式执行操作,如果当前事务存在则抛出异常。
  • PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作

事务的隔离级别:

  • read uncommited:是最低的事务隔离级别,它允许另外一个事务可以看到这个事务未提交的数据。
  • read commited:保证一个事物提交后才能被另外一个事务读取。另外一个事务不能读取该事物未提交的数据。
  • repeatable read:这种事务隔离级别可以防止脏读,不可重复读。但是可能会出现幻象读。它除了保证一个事务不能被另外一个事务读取未提交的数据之外还避免了以下情况产生(不可重复读)。
  • serializable:这是花费最高代价但最可靠的事务隔离级别。事务被处理为顺序执行。除了防止脏读,不可重复读之外,还避免了幻象读。

脏读、不可重复读、幻象读概念说明:

  • 脏读:指当一个事务正字访问数据,并且对数据进行了修改,而这种数据还没有提交到数据库中,这时,另外一个事务也访问这个数据,然后使用了这个数据。因为这个数据还没有提交那么另外一个事务读取到的这个数据我们称之为脏数据。依据脏数据所做的操作肯能是不正确的。
  • 不可重复读:指在一个事务内,多次读同一数据。在这个事务还没有执行结束,另外一个事务也访问该同一数据,那么在第一个事务中的两次读取数据之间,由于第二个事务的修改第一个事务两次读到的数据可能是不一样的,这样就发生了在一个事物内两次连续读到的数据是不一样的,这种情况被称为是不可重复读。
  • 幻象读:一个事务先后读取一个范围的记录,但两次读取的纪录数不同,我们称之为幻象读(两次执行同一条 select 语句会出现不同的结果,第二次读会增加一数据行,并没有说这两次执行是在同一个事务中)

(2).PlatformTransactionManager

从方法名称就可以看出意思;

①TransactionStatus代表一个事务的具体运行状态,事务管理器通过该接口获取事务的运行期状态信息,也可以通过该接口间接地回滚事务,它相比于在抛出异常时回滚事务的方式更具有可控性。该接口继承于SavepointManager接口,SavepointManager接口基于JDBC3.0保存点的分段事务控制能力提供了嵌套事务的机制。

其中,SavepointManager接口拥有以下的方法:

  • Object createSavepoint():创建一个保存点对象,以便在后面可以利用rollbackToSavepoint(Object savepoint)方法使事务回滚到特定的保存点上,也可以通过releaseSavepoint()释放一个已经不用的保存点。
  • void rollbackToSavepoint(Object savepoint):将事务回滚到特定保存点上,被回滚的保存点将自动释放。
  • void releaseSavepoint(Object savepoint):释放一个保存点,如果事务提交,所有保存点会被自动释放,无须手工清除。 这3个方法在底层资源不支持保存点时,都将抛出NestedTransactionNotSupportedException异常。

②TransactionStatus扩展了SavepointManager并提供了以下方法:

  • boolean hasSavepoint():判断当前的事务是否在内部创建了一个保存点,保存点是为了支持Spring的嵌套事务而创建的。
  • boolean isNewTransaction():判断当前事务是否是一个新的事务,如果返回false,表示当前事务是一个已经存在的事务,或者当前操作未运行在事务环境中。
  • boolean isCompleted():判断当前事务是否已经结束(已经提交或回滚)。
  • boolean isRollbackOnly():判断当前事务是否已经被标识为rollback-only。
  • void setRollbackOnly():将当前的事务设置为rollback-only,通过该标识通知事务管理器只能将事务回滚,事务管理器将显式调用回滚命令或以抛出异常的方式回滚事务。

(3). DataSourceTransactionManager分析

(a).getTransaction 开始事物
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
   public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
       //1.获取Connection,ThreadLocal获取;
       Object transaction = doGetTransaction();

       // Cache debug flag to avoid repeated checks.
       boolean debugEnabled = logger.isDebugEnabled();

       if (definition == null) {
           // Use defaults if no transaction definition given.
           definition = new DefaultTransactionDefinition();
       }
       //判断Connection是否为空
       if (isExistingTransaction(transaction)) {
           // Existing transaction found -> check propagation behavior to find out how to behave.
           // 2.处理ThreadLocal获取Connection不为空情况;事务传播情况
           return handleExistingTransaction(definition, transaction, debugEnabled);
       }

       // Check definition settings for new transaction.
       if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
           throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
       }

       // No existing transaction found -> check propagation behavior to find out how to proceed.
       // TransactionDefinition.PROPAGATION_MANDATORY 使用当前事务,如果没有当前事务,就抛出异常。
       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
           throw new IllegalTransactionStateException(
                   "No existing transaction found for transaction marked with propagation 'mandatory'");
       }
       else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
               definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
           definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {//如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
           //3.事物挂起操作;
           SuspendedResourcesHolder suspendedResources = suspend(null);
           if (debugEnabled) {
               logger.debug("Creating new transaction with name [" + definition.getName() + "]: " + definition);
           }
           try {
               boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
               //4.创建DefaultTransactionStatus
               DefaultTransactionStatus status = newTransactionStatus(
                       definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
               //5.开启事物
               // (1).从数据源获取Connection
               // (2).Connection设置隔离级别
               // (3).设置AutoCommit为false
               //(4).Connection保存到ThreadLocal
               doBegin(transaction, definition);
               //6.设置事物值(隔离级别,事物名称,可读状态)保存到ThreadLocal
               prepareSynchronization(status, definition);
               return status;
           }
           catch (RuntimeException ex) {
               //重置上个事物
               resume(null, suspendedResources);
               throw ex;
           }
           catch (Error err) {
               resume(null, suspendedResources);
               throw err;
           }
       }
       else {
           // Create "empty" transaction: no actual transaction, but potentially synchronization.
           //创建“空”事务:没有实际事务,但可能是同步。
           boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
           return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
       }
   }
   @Override
   protected Object doGetTransaction() {
       DataSourceTransactionObject txObject = new DataSourceTransactionObject();
       txObject.setSavepointAllowed(isNestedTransactionAllowed());
       ConnectionHolder conHolder =
               (ConnectionHolder) TransactionSynchronizationManager.getResource(this.dataSource);
       txObject.setConnectionHolder(conHolder, false);
       return txObject;
   }	
(b).handleExistingTransaction 处理ThreadLocal获取Connection不为空情况;事务传播情况
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
   private TransactionStatus handleExistingTransaction(
           TransactionDefinition definition, Object transaction, boolean debugEnabled)
           throws TransactionException {

       //以非事务方式执行操作,如果当前事务存在则抛出异常。
       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
           throw new IllegalTransactionStateException(
                   "Existing transaction found for transaction marked with propagation 'never'");
       }
      //以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
           if (debugEnabled) {
               logger.debug("Suspending current transaction");
           }
           //挂起事物;
           Object suspendedResources = suspend(transaction);
           boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
           //创建事物行为状态
           return prepareTransactionStatus(
                   definition, null, false, newSynchronization, debugEnabled, suspendedResources);
       }
       //新建事务,如果当前存在事务,把当前事务挂起。
       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
           if (debugEnabled) {
               logger.debug("Suspending current transaction, creating new transaction with name [" +
                       definition.getName() + "]");
           }
           //事务挂起。
           SuspendedResourcesHolder suspendedResources = suspend(transaction);
           try {
               boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
               DefaultTransactionStatus status = newTransactionStatus(
                       definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
               //重新创建一个Connection
               doBegin(transaction, definition);
               prepareSynchronization(status, definition);
               return status;
           }
           catch (RuntimeException beginEx) {
               resumeAfterBeginException(transaction, suspendedResources, beginEx);
               throw beginEx;
           }
           catch (Error beginErr) {
               resumeAfterBeginException(transaction, suspendedResources, beginErr);
               throw beginErr;
           }
       }
       //如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
       if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
           //是否支持嵌套事务行为
           if (!isNestedTransactionAllowed()) {
               throw new NestedTransactionNotSupportedException(
                       "Transaction manager does not allow nested transactions by default - " +
                       "specify 'nestedTransactionAllowed' property with value 'true'");
           }
           if (debugEnabled) {
               logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
           }
           //返回是否对嵌套事务使用保存点。
           if (useSavepointForNestedTransaction()) {
               // Create savepoint within existing Spring-managed transaction,
               //在现有的Spring管理的事务中创建保存点,
               // through the SavepointManager API implemented by TransactionStatus.
               //通过TransactionStatus实现的SavepointManager API。
               // Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
               //通常使用JDBC 3.0保存点。, 永远不会激活Spring同步
               DefaultTransactionStatus status =
                       prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
               //创建Savepoint
               status.createAndHoldSavepoint();
               return status;
           }
           else {
               // Nested transaction through nested begin and commit/rollback calls.
               //嵌套事务通过嵌套的begin和commit / rollback调用。
               // Usually only for JTA: Spring synchronization might get activated here
               // in case of a pre-existing JTA transaction.
               //通常仅适用于JTA:如果存在预先存在的JTA事务,则可能会在此处激活Spring同步。
               boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
               DefaultTransactionStatus status = newTransactionStatus(
                       definition, transaction, true, newSynchronization, debugEnabled, null);
               doBegin(transaction, definition);
               prepareSynchronization(status, definition);
               return status;
           }
       }

       // Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
       // 操作  PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
       if (debugEnabled) {
           logger.debug("Participating in existing transaction");
       }
       if (isValidateExistingTransaction()) {
           if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
               Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
               if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
                   Constants isoConstants = DefaultTransactionDefinition.constants;
                   throw new IllegalTransactionStateException("Participating transaction with definition [" +
                           definition + "] specifies isolation level which is incompatible with existing transaction: " +
                           (currentIsolationLevel != null ?
                                   isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
                                   "(unknown)"));
               }
           }
           if (!definition.isReadOnly()) {
               if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
                   throw new IllegalTransactionStateException("Participating transaction with definition [" +
                           definition + "] is not marked as read-only but existing transaction is");
               }
           }
       }
       boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
       return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
   }
(c).commit(TransactionStatus status) 事物提交
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
   public final void commit(TransactionStatus status) throws TransactionException {
       if (status.isCompleted()) {
           throw new IllegalTransactionStateException(
                   "Transaction is already completed - do not call commit or rollback more than once per transaction");
       }

       DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
       //处理回滚操作
       if (defStatus.isLocalRollbackOnly()) {
           if (defStatus.isDebug()) {
               logger.debug("Transactional code has requested rollback");
           }
           processRollback(defStatus);
           return;
       }
       //全局事务标记为仅回滚,但事务代码请求提交
       if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
           if (defStatus.isDebug()) {
               logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
           }
           processRollback(defStatus);
           // Throw UnexpectedRollbackException only at outermost transaction boundary
           // or if explicitly asked to.
           if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
               throw new UnexpectedRollbackException(
                       "Transaction rolled back because it has been marked as rollback-only");
           }
           return;
       }
       //处理提交
       processCommit(defStatus);
   }
   
   private void processCommit(DefaultTransactionStatus status) throws TransactionException {
       try {
           boolean beforeCompletionInvoked = false;
           try {
               prepareForCommit(status);
               triggerBeforeCommit(status);
               triggerBeforeCompletion(status);
               beforeCompletionInvoked = true;
               boolean globalRollbackOnly = false;
               if (status.isNewTransaction() || isFailEarlyOnGlobalRollbackOnly()) {
                   globalRollbackOnly = status.isGlobalRollbackOnly();
               }
               //是否Savepoint
               if (status.hasSavepoint()) {
                   if (status.isDebug()) {
                       logger.debug("Releasing transaction savepoint");
                   }
                   status.releaseHeldSavepoint();
               }
               else if (status.isNewTransaction()) {
                   if (status.isDebug()) {
                       logger.debug("Initiating transaction commit");
                   }
                   //con.commit(); 处理提交
                   doCommit(status);
               }
               // Throw UnexpectedRollbackException if we have a global rollback-only
               // marker but still didn't get a corresponding exception from commit.
               //如果我们有一个全局回滚专用标记,但仍未从提交中获得相应的异常,则抛出UnexpectedRollbackException。
               if (globalRollbackOnly) {
                   throw new UnexpectedRollbackException(
                           "Transaction silently rolled back because it has been marked as rollback-only");
               }
           }
           catch (UnexpectedRollbackException ex) {
               // can only be caused by doCommit
               triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
               throw ex;
           }
           catch (TransactionException ex) {
               // can only be caused by doCommit
               if (isRollbackOnCommitFailure()) {
                   doRollbackOnCommitException(status, ex);
               }
               else {
                   triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
               }
               throw ex;
           }
           catch (RuntimeException ex) {
               if (!beforeCompletionInvoked) {
                   triggerBeforeCompletion(status);
               }
               doRollbackOnCommitException(status, ex);
               throw ex;
           }
           catch (Error err) {
               if (!beforeCompletionInvoked) {
                   triggerBeforeCompletion(status);
               }
               doRollbackOnCommitException(status, err);
               throw err;
           }

           // Trigger afterCommit callbacks, with an exception thrown there
           // propagated to callers but the transaction still considered as committed.
           try {
               triggerAfterCommit(status);
           }
           finally {
               triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
           }

       }
       finally {
           //有传播事物,重置上个事物
           cleanupAfterCompletion(status);
       }
   }	
(d).rollback(TransactionStatus status) 回滚
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
   public final void rollback(TransactionStatus status) throws TransactionException {
       if (status.isCompleted()) {
           throw new IllegalTransactionStateException(
                   "Transaction is already completed - do not call commit or rollback more than once per transaction");
       }

       DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
       processRollback(defStatus);
   }

   /**
    * Process an actual rollback.
    * The completed flag has already been checked.
    * @param status object representing the transaction
    * @throws TransactionException in case of rollback failure
    */
   private void processRollback(DefaultTransactionStatus status) {
       try {
           try {
               triggerBeforeCompletion(status);
               if (status.hasSavepoint()) {
                   if (status.isDebug()) {
                       logger.debug("Rolling back transaction to savepoint");
                   }
                   //回滚Savepoint
                   status.rollbackToHeldSavepoint();
               }
               else if (status.isNewTransaction()) {
                   if (status.isDebug()) {
                       logger.debug("Initiating transaction rollback");
                   }
                   //con.rollback();回滚操作
                   doRollback(status);
               }
               else if (status.hasTransaction()) {
                   if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
                       if (status.isDebug()) {
                           logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
                       }
                       //txObject.setRollbackOnly(); 标示回滚操作
                       doSetRollbackOnly(status);
                   }
                   else {
                       if (status.isDebug()) {
                           logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
                       }
                   }
               }
               else {
                   logger.debug("Should roll back transaction but cannot - no transaction available");
               }
           }
           catch (RuntimeException ex) {
               triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
               throw ex;
           }
           catch (Error err) {
               triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
               throw err;
           }
           triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
       }
       finally {
           //有传播事物,重置上个事物
           cleanupAfterCompletion(status);
       }
   } 

(4).createTransactionIfNecessary 事物开启

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
   protected TransactionInfo createTransactionIfNecessary(
           PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {

       // If no name specified, apply method identification as transaction name.
       if (txAttr != null && txAttr.getName() == null) {
           txAttr = new DelegatingTransactionAttribute(txAttr) {
               @Override
               public String getName() {
                   return joinpointIdentification;
               }
           };
       }

       TransactionStatus status = null;
       if (txAttr != null) {
           if (tm != null) {
               status = tm.getTransaction(txAttr);//开启事务,调用PlatformTransactionManager
           }
           else {
               if (logger.isDebugEnabled()) {
                   logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
                           "] because no transaction manager has been configured");
               }
           }
       }
       //创建TransactionInfo,保存Threadlocal
       return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
   }

(5).completeTransactionAfterThrowing(txInfo, ex);事物异常处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
   protected void completeTransactionAfterThrowing(TransactionInfo txInfo, Throwable ex) {
       if (txInfo != null && txInfo.hasTransaction()) {
           if (logger.isTraceEnabled()) {
               logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
                       "] after exception: " + ex);
           }
           // 默认(ex instanceof RuntimeException || ex instanceof Error);
           if (txInfo.transactionAttribute.rollbackOn(ex)) {//验证配置回滚异常类
               try {
                   txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());//进行回滚
               }
               catch (TransactionSystemException ex2) {
                   logger.error("Application exception overridden by rollback exception", ex);
                   ex2.initApplicationException(ex);
                   throw ex2;
               }
               catch (RuntimeException ex2) {
                   logger.error("Application exception overridden by rollback exception", ex);
                   throw ex2;
               }
               catch (Error err) {
                   logger.error("Application exception overridden by rollback error", ex);
                   throw err;
               }
           }
           else {
               // We don't roll back on this exception.
               // Will still roll back if TransactionStatus.isRollbackOnly() is true.
               try {
                   txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());//直接提交,不进行回滚
               }
               catch (TransactionSystemException ex2) {
                   logger.error("Application exception overridden by commit exception", ex);
                   ex2.initApplicationException(ex);
                   throw ex2;
               }
               catch (RuntimeException ex2) {
                   logger.error("Application exception overridden by commit exception", ex);
                   throw ex2;
               }
               catch (Error err) {
                   logger.error("Application exception overridden by commit error", ex);
                   throw err;
               }
           }
       }
   }

二、XML解析

TransactionAttributeSource实现类是NameMatchTransactionAttributeSource;处理事物逻辑 TransactionInterceptor;这里就不做具体分析;