publicabstractclassAbstractPlatformTransactionManagerimplementsPlatformTransactionManager,Serializable{protectedfinalSuspendedResourcesHoldersuspend(@NullableObjecttransaction)throwsTransactionException{if(TransactionSynchronizationManager.isSynchronizationActive()){List<TransactionSynchronization>suspendedSynchronizations=doSuspendSynchronization();try{ObjectsuspendedResources=null;if(transaction!=null){// TODO 重点:如果存在事务,则挂起事务,其实就是从ThreadLocal变量中解绑连接。suspendedResources=doSuspend(transaction);}// 清楚TransactionSynchronizationManager中的当前事务的一些信息。将旧的事务对象信息封装到挂起对象中,最终会绑定到当前事务对象。Stringname=TransactionSynchronizationManager.getCurrentTransactionName();TransactionSynchronizationManager.setCurrentTransactionName(null);booleanreadOnly=TransactionSynchronizationManager.isCurrentTransactionReadOnly();TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);IntegerisolationLevel=TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);booleanwasActive=TransactionSynchronizationManager.isActualTransactionActive();TransactionSynchronizationManager.setActualTransactionActive(false);// 返回一个挂起资源持有对象,这个对象中封装了当前已存在事务的具体信息。这个对象会存储到新开启事务的TransactionStatus中。returnnewSuspendedResourcesHolder(suspendedResources,suspendedSynchronizations,name,readOnly,isolationLevel,wasActive);}catch(RuntimeException|Errorex){// doSuspend failed - original transaction is still active...doResumeSynchronization(suspendedSynchronizations);throwex;}}elseif(transaction!=null){// Transaction active but no synchronization active.ObjectsuspendedResources=doSuspend(transaction);returnnewSuspendedResourcesHolder(suspendedResources);}else{// Neither transaction nor synchronization active.returnnull;}}}
publicclassDataSourceTransactionManagerextendsAbstractPlatformTransactionManagerimplementsResourceTransactionManager,InitializingBean{privatestaticObjectdoUnbindResource(ObjectactualKey){// 从ThreadLocal的map缓存中获取,如果为空,直接返回,如果不为空,则移除绑定关系。Map<Object,Object>map=resources.get();if(map==null){returnnull;}// 这里会解绑当前线程的链接资源。Objectvalue=map.remove(actualKey);// Remove entire ThreadLocal if empty...if(map.isEmpty()){resources.remove();}// Transparently suppress a ResourceHolder that was marked as void...if(valueinstanceofResourceHolder&&((ResourceHolder)value).isVoid()){value=null;}if(value!=null&&logger.isTraceEnabled()){logger.trace("Removed value ["+value+"] for key ["+actualKey+"] from thread ["+Thread.currentThread().getName()+"]");}returnvalue;}}
publicabstractclassTransactionAspectSupportimplementsBeanFactoryAware,InitializingBean{protectedvoidcommitTransactionAfterReturning(@NullableTransactionInfotxInfo){if(txInfo!=null&&txInfo.getTransactionStatus()!=null){if(logger.isTraceEnabled()){logger.trace("Completing transaction for ["+txInfo.getJoinpointIdentification()+"]");}// 使用事务管理器,提交事务。txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());}}}
publicabstractclassAbstractPlatformTransactionManagerimplementsPlatformTransactionManager,Serializable{@Overridepublicfinalvoidcommit(TransactionStatusstatus)throwsTransactionException{if(status.isCompleted()){thrownewIllegalTransactionStateException("Transaction is already completed - do not call commit or rollback more than once per transaction");}DefaultTransactionStatusdefStatus=(DefaultTransactionStatus)status;// TODO 如果事务信息中保存的是仅回滚,则进行回滚操作。比如假如到这个事务中的方法抛出异常,// 则不会再那个方法就回滚,而是返回到事务的起点方法后,再进行回滚操作。if(defStatus.isLocalRollbackOnly()){if(defStatus.isDebug()){logger.debug("Transactional code has requested rollback");}// 回滚事务processRollback(defStatus,false);return;}// 判断是否仅回滚,主要是看connectionHolder是否设置了仅回滚。if(!shouldCommitOnGlobalRollbackOnly()&&defStatus.isGlobalRollbackOnly()){if(defStatus.isDebug()){logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");}// 回滚事务processRollback(defStatus,true);return;}// TODO 事务提交processCommit(defStatus);}}
publicclassRuleBasedTransactionAttributeextendsDefaultTransactionAttributeimplementsSerializable{@OverridepublicbooleanrollbackOn(Throwableex){RollbackRuleAttributewinner=null;intdeepest=Integer.MAX_VALUE;// 判断回滚规则if(this.rollbackRules!=null){for(RollbackRuleAttributerule:this.rollbackRules){// 递归调用异常的父类,如果异常名称中包含规则中封装的异常名称,则返回。intdepth=rule.getDepth(ex);// 如果不满足规则,会返回-1,如果满足了规则,会把这个规则赋值到winner临时变量中。if(depth>=0&&depth<deepest){deepest=depth;winner=rule;}}}if(logger.isTraceEnabled()){logger.trace("Winning rollback rule is: "+winner);}// 如果没有配置回滚异常或不回滚异常,则会走默认的。默认回滚运行时异常及Error:// (ex instanceof RuntimeException || ex instanceof Error);// User superclass behavior (rollback on unchecked) if no rule matches.if(winner==null){logger.trace("No relevant rollback rule found: applying default rules");returnsuper.rollbackOn(ex);}// 判断规则如果是不回滚规则,则返回false,表示不需要回滚。// 判断规则如果不是不回滚规则,返回true,表示需要回滚return!(winnerinstanceofNoRollbackRuleAttribute);}}
publicabstractclassAbstractPlatformTransactionManagerimplementsPlatformTransactionManager,Serializable{privatevoidprocessRollback(DefaultTransactionStatusstatus,booleanunexpected){try{booleanunexpectedRollback=unexpected;try{// 如果是一个新建的事务,即到了事务的起点。// 在回滚之前会循环调用TransactionSynchronization的beforeCompletion方法,这里是一个回调函数triggerBeforeCompletion(status);// 有保存点(或者叫回滚点),回滚到保存点位置if(status.hasSavepoint()){if(status.isDebug()){logger.debug("Rolling back transaction to savepoint");}status.rollbackToHeldSavepoint();}// 如果是一个新建的事务,即回到了事务的起点。elseif(status.isNewTransaction()){if(status.isDebug()){logger.debug("Initiating transaction rollback");}// 从当前事务状态对象中获取到链接对象,进行回滚操作doRollback(status);}else{// 如果是加入的已有事务,则将事务状态设置为仅回滚 rollbackOnly=true,最终返回到事务的起点时,是否向外抛出异常都会回滚。// 所以在 REQUIRED 传播行为中,任何一个加入事务的方法异常,都会触发回滚。// Participating in larger transactionif(status.hasTransaction()){if(status.isLocalRollbackOnly()||isGlobalRollbackOnParticipationFailure()){if(status.isDebug()){logger.debug("Participating transaction failed - marking existing transaction as rollback-only");}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");}// Unexpected rollback only matters here if we're asked to fail earlyif(!isFailEarlyOnGlobalRollbackOnly()){unexpectedRollback=false;}}}catch(RuntimeException|Errorex){// TransactionSynchronization 扩展点triggerAfterCompletion(status,TransactionSynchronization.STATUS_UNKNOWN);throwex;}// 事务提交后,获取事务同步器进行循环调用,TransactionSynchronization.afterCompletiontriggerAfterCompletion(status,TransactionSynchronization.STATUS_ROLLED_BACK);// Raise UnexpectedRollbackException if we had a global rollback-only markerif(unexpectedRollback){thrownewUnexpectedRollbackException("Transaction rolled back because it has been marked as rollback-only");}}finally{cleanupAfterCompletion(status);}}}