【spring】事務底層的實現流程

zfcq發表於2022-03-10

事務簡單介紹

  • 本文原始碼基於spring-framework-5.3.10。
  • 事務是基於AOP的機制進行實現的!

Spring事務基本執行原理

  • 一個Bean在執行Bean的建立生命週期時,會經過InfrastructureAdvisorAutoProxyCreator的初始化後的方法,會判斷當前當前Bean物件是否和BeanFactoryTransactionAttributeSourceAdvisor匹配,匹配邏輯為判斷該Bean的類上是否存在@Transactional註解,或者類中的某個方法上是否存在@Transactional註解,如果存在則表示該Bean需要進行動態代理產生一個代理物件作為Bean物件。

Spring事務基本執行流程

  • 利用所配置的PlatformTransactionManager事務管理器新建一個資料庫連線。
  • 修改資料庫連線的autocommit為false。
  • 執行MethodInvocation.proceed()方法,簡單理解就是執行業務方法,其中就會執行sql。
  • 如果沒有拋異常,則提交。
  • 如果拋了異常,則回滾。

原始碼執行流程

  • 加了@Transactional註解的類,或者類中擁有@Transactional註解的方法,都會生成代理物件作為bean。
  • 代理物件執行方法時。
  • 獲取當前正在執行的方法上的@Transactional註解的資訊TransactionAttribute。
  • 檢視@Transactional註解上是否指定了TransactionManager,如果沒有指定,則預設獲取TransactionManager型別的bean作為TransactionManager。
  • 對於TransactionManager有一個限制,必須是PlatformTransactionManager。
  • 生成一個joinpointIdentification,作為事務的名字。
  • 開始建立事務。
  • 建立事務成功後執行業務方法。
  • 如果執行業務方法出現異常,則會進行回滾,然後執行完finally中的方法後再將異常丟擲。
  • 如果執行業務方法沒有出現異常,那麼則會執行完finally中的方法後再進行提交。

建立事務原始碼流程

  • 得到一個TransactionStatus物件、
  • 將PlatformTransactionManager、TransactionAttribute、TransactionStatus構造成為一個TransactionInfo物件,並返回TransactionInfo物件。

回滾事務原始碼流程

  • 判斷當前異常是否需要回滾。不需要回滾直接走提價的流程。
  • 觸發同步器的beforeCompletion()。
  • 呼叫資料庫連線物件的rollback()。
  • 觸發同步器的afterCompletion()。
  • 判斷是否有事務掛起。
  • 如果有則把掛起的事務重新設定到TransactionSynchronizationManager中去,並執行同步器的resume()方法。

提交事務原始碼流程

  • 觸發同步器的beforeCommit。
  • 觸發同步器的beforeCompletion()。
  • 呼叫資料庫連線物件的commit()。
  • 觸發同步器的afterCommit。
  • 觸發同步器的afterCompletion()。
  • 判斷是否有事務掛起。
  • 如果有則把掛起的事務重新設定到TransactionSynchronizationManager中去,並執行同步器的resume()方法。

建立TransactionStatus的原始碼流程

  • 呼叫AbstractPlatformTransactionManager類中的getTransaction(txAttr)方法,實際上這個方法就是真正去開啟事務的方法。
  • 呼叫DataSourceTransactionManager中的doGetTransaction()得到一個事務物件,得到的事務物件中可能持有也可能沒有持有資料庫連線物件。不同船舶機制下,是否持有事務,邏輯不同!
傳播機制 含義 之前方法持有事務的邏輯 之前方法未持有事務的邏輯
REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED) 支援當前事務,如果沒有事務會建立一個新的事務 在當前事務執行 建立一個新的事務
SUPPORTS(TransactionDefinition.PROPAGATION_SUPPORTS) 支援當前事務,如果沒有事務的話以非事務方式執行 在當前事務執行 使用非事務的方式執行
MANDATORY(TransactionDefinition.PROPAGATION_MANDATORY) 支援當前事務,如果沒有事務丟擲異常 在當前事務執行 拋異常
REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW) 建立一個新的事務並掛起當前事務 建立一個新的事務並掛起當前事務 建立一個新的事務
NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED) 以非事務方式執行,如果當前存在事務則將當前事務掛起 掛起當前事務 使用非事務的方式執行
NEVER(TransactionDefinition.PROPAGATION_NEVER) 以非事務方式進行,如果存在事務則丟擲異常 拋異常 使用非事務的方式執行
NESTED(TransactionDefinition.PROPAGATION_NESTED) 如果當前存在事務,則在巢狀事務內執行。如果當前沒有事務,則建立一個新事務 利用資料庫連線物件,設定一個savepoint,比如mysql就支援,在一個事務中,可以在某個位置設定一個savepoint,後續可以只回滾到某個savepoint 建立一個新的事務

doBegin原始碼流程

  • 如果事務物件中沒有持有資料庫連線物件,那麼則呼叫DataSource獲取一個資料庫連線物件,並設定到事務物件中去
  • 設定當前資料庫連線的隔離級別。
  • 設定資料庫連線的autoCommit為false。
  • 設定資料庫連線的timeout。
  • 把獲得的資料庫連線物件通過TransactionSynchronizationManager設定到當前執行緒的ThreadLocal中。

同步器使用方式

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
        @Override
        public void afterCommit() {
            System.out.println("after commit...");
        }
}

開啟事務的註解@EnableTransactionManagement原始碼分析

/**
 * 這個註解匯入了TransactionManagementConfigurationSelector類
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {

	boolean proxyTargetClass() default false;

	AdviceMode mode() default AdviceMode.PROXY;

	int order() default Ordered.LOWEST_PRECEDENCE;
}

匯入的TransactionManagementConfigurationSelector原始碼分析

/**
 * 在呼叫process方法的時候會呼叫到這裡
 */
protected String[] selectImports(AdviceMode adviceMode) {
	switch (adviceMode) {
		case PROXY:
			// 預設是PROXY。往Spring容器中新增了兩個Bean:AutoProxyRegistrar、ProxyTransactionManagementConfiguration
			return new String[] {AutoProxyRegistrar.class.getName(),
					ProxyTransactionManagementConfiguration.class.getName()};
		case ASPECTJ:
			// 表示不用動態代理技術,用ASPECTJ技術,比較麻煩了
			return new String[] {determineTransactionAspectClass()};
		default:
			return null;
	}
}

AutoProxyRegistrar的Bean原始碼分析

/**
 * 這個類實現了ImportBeanDefinitionRegistrar,他在啟動的時候會呼叫registerBeanDefinitions方法。
 * 最核心的邏輯是往Spring容器中註冊了一個InfrastructureAdvisorAutoProxyCreator的Bean。
 * InfrastructureAdvisorAutoProxyCreator繼承了AbstractAdvisorAutoProxyCreator,所以這個類的主要作用就是開啟自動代理的作用,也就是一個BeanPostProcessor,會在初始化後步驟中去尋找Advisor型別的Bean,並判斷當前某個Bean是否有匹配的Advisor,是否需要利用動態代理產生一個代理物件。
 */
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		boolean candidateFound = false;
		Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
		for (String annType : annTypes) {
			AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
			if (candidate == null) {
				continue;
			}
			Object mode = candidate.get("mode");
			Object proxyTargetClass = candidate.get("proxyTargetClass");
			if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
					Boolean.class == proxyTargetClass.getClass()) {
				candidateFound = true;
				if (mode == AdviceMode.PROXY) {
					// 註冊InfrastructureAdvisorAutoProxyCreator,才可以Bean進行AOP
					AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
					if ((Boolean) proxyTargetClass) {
						// 設定InfrastructureAdvisorAutoProxyCreator的proxyTargetClass為true
						AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
						return;
					}
				}
			}
		}
		if (!candidateFound && logger.isInfoEnabled()) {
			String name = getClass().getSimpleName();
			logger.info(String.format("%s was imported but no annotations were found " +
					"having both 'mode' and 'proxyTargetClass' attributes of type " +
					"AdviceMode and boolean respectively. This means that auto proxy " +
					"creator registration and configuration may not have occurred as " +
					"intended, and components may not be proxied as expected. Check to " +
					"ensure that %s has been @Import'ed on the same class where these " +
					"annotations are declared; otherwise remove the import of %s " +
					"altogether.", name, name, name));
		}
	}
}

匯入的ProxyTransactionManagementConfiguration原始碼分析

/**
 * ProxyTransactionManagementConfiguration是一個配置類,它又定義了另外三個bean:
 * BeanFactoryTransactionAttributeSourceAdvisor:一個Advisor
 * AnnotationTransactionAttributeSource:相當於BeanFactoryTransactionAttributeSourceAdvisor中的Pointcut
 * TransactionInterceptor:相當於BeanFactoryTransactionAttributeSourceAdvisor中的Advice
 */
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

	// 定義一個Advisor的Bean
	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	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;
	}

	// 定義Advisor的Pointcut
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionAttributeSource transactionAttributeSource() {
		// AnnotationTransactionAttributeSource中定義了一個Pointcut
		// 並且AnnotationTransactionAttributeSource可以用來解析@Transactional註解,並得到一個RuleBasedTransactionAttribute物件
		return new AnnotationTransactionAttributeSource();
	}

	// 定義Advisor的Advice
	// 開啟事務、回滾、提交都在這個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;
	}

}

使用用到的Pointcut原始碼分析

public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {

	/**
	 * pointcut就是一個new TransactionAttributeSourcePointcut物件
	 */
	private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
		@Override
		@Nullable
		protected TransactionAttributeSource getTransactionAttributeSource() {
			return transactionAttributeSource;
		}
	};

	/**
	 * 獲取pointcut採用的是內部類的方式構建
	 */
	@Override
	public Pointcut getPointcut() {
		return this.pointcut;
	}

}

/**
 * 構建Pointcut用到的類
 */
abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {

	// 外部構造方法呼叫到這裡,其實就是設定new TransactionAttributeSourceClassFilter()
	// 這裡面主要進行類的判斷
	protected TransactionAttributeSourcePointcut() {
		setClassFilter(new TransactionAttributeSourceClassFilter());
	}

	// 判斷方法是否匹配
	@Override
	public boolean matches(Method method, Class<?> targetClass) {
		// 呼叫外部重寫的方法
		TransactionAttributeSource tas = getTransactionAttributeSource();
		return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
	}

	// 具體的匹配邏輯
	private class TransactionAttributeSourceClassFilter implements ClassFilter {

		@Override
		public boolean matches(Class<?> clazz) {
			// 事務內部的一些類,直接返回false
			if (TransactionalProxy.class.isAssignableFrom(clazz) ||
					TransactionManager.class.isAssignableFrom(clazz) ||
					PersistenceExceptionTranslator.class.isAssignableFrom(clazz)) {
				return false;
			}
			// 呼叫外部重寫的方法
			TransactionAttributeSource tas = getTransactionAttributeSource();
			// 判斷有沒有@Transaction註解
			return (tas == null || tas.isCandidateClass(clazz));
		}
	}
}

/**
 * 原始碼位置:org.springframework.transaction.annotation.AnnotationTransactionAttributeSource.isCandidateClass(Class<?>)
 * 判斷是否能成為候選者
 */
public boolean isCandidateClass(Class<?> targetClass) {
	for (TransactionAnnotationParser parser : this.annotationParsers) {
		if (parser.isCandidateClass(targetClass)) {
			return true;
		}
	}
	return false;
}

/**
 * 原始碼位置:org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getTransactionAttribute(Method, Class<?>)
 * 判斷當前類上面是否有@Transactional註解
 */
public boolean isCandidateClass(Class<?> targetClass) {
	return AnnotationUtils.isCandidateClass(targetClass, Transactional.class);
}

/**
 * 原始碼位置:org.springframework.transaction.annotation.SpringTransactionAnnotationParser.isCandidateClass(Class<?>)
 * 獲取方法上或者類上是否有@Transaction註解
 */
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
	// Object類直接返回null
	if (method.getDeclaringClass() == Object.class) {
		return null;
	}

	// First, see if we have a cached value.
	// 檢查快取裡的結果,快取裡存了當前類和方法是否存在Transactional註解
	Object cacheKey = getCacheKey(method, targetClass);
	TransactionAttribute cached = this.attributeCache.get(cacheKey);
	if (cached != null) {
		// Value will either be canonical value indicating there is no transaction attribute,
		// or an actual transaction attribute.
		// 快取中沒有,直接返回null
		if (cached == NULL_TRANSACTION_ATTRIBUTE) {
			return null;
		}
		else {
			return cached;
		}
	}
	else {
		// We need to work it out.
		// 解析。實際物件為RuleBasedTransactionAttribute
		TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
		// Put it in the cache.
		// 為空,快取一個空的
		if (txAttr == null) {
			this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
		}
		else {
			String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
			if (txAttr instanceof DefaultTransactionAttribute) {
				DefaultTransactionAttribute dta = (DefaultTransactionAttribute) txAttr;
				dta.setDescriptor(methodIdentification);
				dta.resolveAttributeStrings(this.embeddedValueResolver);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
			}
			// 不為空,快取結果
			this.attributeCache.put(cacheKey, txAttr);
		}
		return txAttr;
	}
}

最終執行的Advisor:TransactionInterceptor原始碼分析

/**
 * 原始碼位置:org.springframework.transaction.interceptor.TransactionInterceptor.invoke(MethodInvocation)
 */
public Object invoke(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 CoroutinesInvocationCallback() {
		@Override
		@Nullable
		public Object proceedWithInvocation() throws Throwable {
			// 執行後續的Interceptor,以及被代理的方法
			return invocation.proceed(); // test() sql
		}
		@Override
		public Object getTarget() {
			return invocation.getThis();
		}
		@Override
		public Object[] getArguments() {
			return invocation.getArguments();
		}
	});
}

/**
 * 具體的執行程式碼
 */
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
		final InvocationCallback invocation) throws Throwable {

	// If the transaction attribute is null, the method is non-transactional.
	// TransactionAttribute就是@Transactional中的配置
	TransactionAttributeSource tas = getTransactionAttributeSource();
	// 獲取@Transactional註解中的屬性值
	final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);

	// 返回Spring容器中型別為TransactionManager的Bean物件。事務的開啟,提交,回滾都會用到TransactionManager物件。
	final TransactionManager tm = determineTransactionManager(txAttr);

	// ReactiveTransactionManager用得少,並且它只是執行方式是響應式的,原理流程和普通的是一樣的
	if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
		boolean isSuspendingFunction = KotlinDetector.isSuspendingFunction(method);
		boolean hasSuspendingFlowReturnType = isSuspendingFunction &&
				COROUTINES_FLOW_CLASS_NAME.equals(new MethodParameter(method, -1).getParameterType().getName());
		if (isSuspendingFunction && !(invocation instanceof CoroutinesInvocationCallback)) {
			throw new IllegalStateException("Coroutines invocation not supported: " + method);
		}
		CoroutinesInvocationCallback corInv = (isSuspendingFunction ? (CoroutinesInvocationCallback) invocation : null);

		ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
			Class<?> reactiveType =
					(isSuspendingFunction ? (hasSuspendingFlowReturnType ? Flux.class : Mono.class) : method.getReturnType());
			ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(reactiveType);
			if (adapter == null) {
				throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
						method.getReturnType());
			}
			return new ReactiveTransactionSupport(adapter);
		});

		InvocationCallback callback = invocation;
		if (corInv != null) {
			callback = () -> CoroutinesUtils.invokeSuspendingFunction(method, corInv.getTarget(), corInv.getArguments());
		}
		Object result = txSupport.invokeWithinTransaction(method, targetClass, callback, txAttr, (ReactiveTransactionManager) tm);
		if (corInv != null) {
			Publisher<?> pr = (Publisher<?>) result;
			return (hasSuspendingFlowReturnType ? KotlinDelegate.asFlow(pr) :
					KotlinDelegate.awaitSingleOrNull(pr, corInv.getContinuation()));
		}
		return result;
	}

	// 把tm強制轉換為PlatformTransactionManager,所以我們在定義時得定義PlatformTransactionManager型別
	PlatformTransactionManager ptm = asPlatformTransactionManager(tm);

	// joinpoint的唯一標識,就是當前在執行的方法名字
	final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

	// CallbackPreferringPlatformTransactionManager表示擁有回撥功能的PlatformTransactionManager,也不常用
	if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
		// Standard transaction demarcation with getTransaction and commit/rollback calls.
		// 如果有必要就建立事務,這裡就涉及到事務傳播機制的實現了
		// TransactionInfo表示一個邏輯事務,比如兩個邏輯事務屬於同一個物理事務
		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.
			// 執行下一個Interceptor或被代理物件中的方法
			retVal = invocation.proceedWithInvocation(); //test
		}
		catch (Throwable ex) {
			// target invocation exception
			// 拋異常了,則回滾事務
			completeTransactionAfterThrowing(txInfo, ex);
			throw ex;
		}
		finally {
			cleanupTransactionInfo(txInfo);
		}

		if (retVal != null && 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);
			}
		}

		// 提交事務
		commitTransactionAfterReturning(txInfo);
		return retVal;
	}

	else {
		Object result;
		final ThrowableHolder throwableHolder = new ThrowableHolder();

		// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
		try {
			result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
				TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
				try {
					Object retVal = invocation.proceedWithInvocation();
					if (retVal != null && 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);
				}
			});
		}
		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;
		}

		// Check result state: It might indicate a Throwable to rethrow.
		if (throwableHolder.throwable != null) {
			throw throwableHolder.throwable;
		}
		return result;
	}
}

/**
 * 建立事務的邏輯
 */
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
		@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {

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

	// 每個邏輯事務都會建立一個TransactionStatus,但是TransactionStatus中有一個屬性代表當前邏輯事務底層的物理事務是不是新的
	TransactionStatus status = null;
	if (txAttr != null) {
		if (tm != null) {
			// 開啟事務!
			status = tm.getTransaction(txAttr);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
						"] because no transaction manager has been configured");
			}
		}
	}

	// 返回一個TransactionInfo物件,表示得到了一個事務,可能是新建立的一個事務,也可能是拿到的已有的事務
	return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}

獲取(開啟)事務的邏輯

/**
 * 獲取事務的邏輯
 * 原始碼位置:org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(TransactionDefinition)
 * definition:Transaction註解的資訊的物件
 */
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
		throws TransactionException {

	// Use defaults if no transaction definition given.
	TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());

	// 從ThreadLocal中拿到txObject物件
	Object transaction = doGetTransaction();
	boolean debugEnabled = logger.isDebugEnabled();

	// transaction.getConnectionHolder().isTransactionActive()
	// 判斷是不是存在一個事務
	if (isExistingTransaction(transaction)) {
		// Existing transaction found -> check propagation behavior to find out how to behave.
		return handleExistingTransaction(def, transaction, debugEnabled);
	}

	// Check definition settings for new transaction.
	// 配置的資料庫返回的超時時間小於-1,拋異常。
	if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
		throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
	}

	// No existing transaction found -> check propagation behavior to find out how to proceed.
	// 當前不存在事務,並且配置的傳播機制為PROPAGATION_MANDATORY(支援當前事務,如果沒有事務丟擲異常),拋異常
	if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
		throw new IllegalTransactionStateException(
				"No existing transaction found for transaction marked with propagation 'mandatory'");
	}
	// 在當前Thread中沒有事務的前提下,以下三個是等價的。
	// PROPAGATION_REQUIRED :支援當前事務,如果沒有事務會建立一個新的事務
	// PROPAGATION_REQUIRES_NEW :建立一個新的事務並掛起當前事務
	// PROPAGATION_NESTED:	如果當前存在事務,則在巢狀事務內執行。如果當前沒有事務,則建立一個事務。
	else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
			def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
			def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
		// 沒有事務需要掛起,不過TransactionSynchronization有可能需要掛起。直接呼叫TransactionSynchronizationManager.initSynchronization方法會有需要被掛起的。
		// suspendedResources表示當前執行緒被掛起的資源持有物件(資料庫連線、TransactionSynchronization)
		SuspendedResourcesHolder suspendedResources = suspend(null);
		if (debugEnabled) {
			logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
		}
		try {
			// 開啟事務方法
			// 開啟事務後,transaction中就會有資料庫連線了,並且isTransactionActive為true
			// 並返回TransactionStatus物件,該物件儲存了很多資訊,包括被掛起的資源
			return startTransaction(def, transaction, debugEnabled, suspendedResources);
		}
		catch (RuntimeException | Error ex) {
			resume(null, suspendedResources);
			throw ex;
		}
	}
	else {
		// Create "empty" transaction: no actual transaction, but potentially synchronization.
		if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
			logger.warn("Custom isolation level specified but no actual transaction initiated; " +
					"isolation level will effectively be ignored: " + def);
		}
		boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
		return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
	}
}

/**
 * 開啟Transaction事務
 */
private TransactionStatus startTransaction(TransactionDefinition definition, Object transaction,
		boolean debugEnabled, @Nullable SuspendedResourcesHolder suspendedResources) {

	// 是否開啟一個新的TransactionSynchronization
	boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);

	// 開啟的這個事務的狀態資訊:
	// 事務的定義、用來儲存資料庫連線的物件、是否是新事務,是否是新的TransactionSynchronization
	DefaultTransactionStatus status = newTransactionStatus(
			definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);

	// 開啟事務
	doBegin(transaction, definition);

	// 如果需要新開一個TransactionSynchronization,就把新建立的事務的一些狀態資訊設定到TransactionSynchronizationManager中
	prepareSynchronization(status, definition);
	return status;
}

/**
 * 開啟事務!DataSource層面
 * 原始碼位置:org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(Object, TransactionDefinition)
 */
protected void doBegin(Object transaction, TransactionDefinition definition) {
	DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
	Connection con = null;

	try {

		// 如果當前執行緒中所使用的DataSource還沒有建立過資料庫連線,就獲取一個新的資料庫連線
		if (!txObject.hasConnectionHolder() ||
				txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
			// 得到連線物件
			Connection newCon = obtainDataSource().getConnection();
			if (logger.isDebugEnabled()) {
				logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
			}
			// 設定到DataSourceTransactionObject。注意這裡設定的true,表示txObject的連結一個新的
			txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
		}

		txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
		// 得到連線物件
		con = txObject.getConnectionHolder().getConnection();

		// 根據@Transactional註解中的設定,設定Connection的readOnly與隔離級別
		Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
		txObject.setPreviousIsolationLevel(previousIsolationLevel);
		txObject.setReadOnly(definition.isReadOnly());

		// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
		// so we don't want to do it unnecessarily (for example if we've explicitly
		// configured the connection pool to set it already).
		// 保證autocommit是false。autocommit為true的時候設定autocommit為false
		if (con.getAutoCommit()) {
			txObject.setMustRestoreAutoCommit(true);
			if (logger.isDebugEnabled()) {
				logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
			}
			con.setAutoCommit(false);
		}

		prepareTransactionalConnection(con, definition);
		txObject.getConnectionHolder().setTransactionActive(true);

		// 設定資料庫連線的過期時間
		int timeout = determineTimeout(definition);
		if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
			txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
		}

		// Bind the connection holder to the thread.
		// 把新建的資料庫連線設定到resources中,resources就是一個ThreadLocal<Map<Object, Object>>,事務管理器中的設定的DataSource物件為key,資料庫連線物件為value
		if (txObject.isNewConnectionHolder()) {
			TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
		}
	}

	catch (Throwable ex) {
		if (txObject.isNewConnectionHolder()) {
			DataSourceUtils.releaseConnection(con, obtainDataSource());
			txObject.setConnectionHolder(null, false);
		}
		throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
	}
}

掛起相關流程

/**
 * 掛起相關流程
 * 原始碼位置:org.springframework.transaction.support.AbstractPlatformTransactionManager.suspend(Object)
 */
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
	// synchronizations是一個ThreadLocal<Set<TransactionSynchronization>>
	// 我們可以在任何地方通過TransactionSynchronizationManager給當前執行緒新增TransactionSynchronization,

	// 這裡判斷有沒有開啟事務。在prepareSynchronization方法中開啟!
	if (TransactionSynchronizationManager.isSynchronizationActive()) {
		// 呼叫TransactionSynchronization的suspend方法,並清空和返回當前執行緒中所有的TransactionSynchronization物件
		List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
		try {
			Object suspendedResources = null;
			if (transaction != null) {
				// 掛起事務,把transaction中的Connection清空,並把resources中的key-value進行移除,並返回資料庫連線Connection物件
				suspendedResources = doSuspend(transaction);
			}

			// 獲取並清空當前執行緒中關於TransactionSynchronizationManager的設定
			String name = TransactionSynchronizationManager.getCurrentTransactionName();
			TransactionSynchronizationManager.setCurrentTransactionName(null);
			boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
			TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
			Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
			TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
			boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
			TransactionSynchronizationManager.setActualTransactionActive(false);

			// 將當前執行緒中的資料庫連線物件、TransactionSynchronization物件、TransactionSynchronizationManager中的設定構造成一個物件
			// 表示被掛起的資源持有物件,持有了當前執行緒中的事務物件、TransactionSynchronization物件
			// suspendedResources資料庫連線、suspendedSynchronizations自己定義的同步器、name事務的名稱、readOnly事務是不是隻讀、isolationLevel事務隔離級別、wasActive切面的Active
			return new SuspendedResourcesHolder(
					suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
		}
		catch (RuntimeException | Error ex) {
			// doSuspend failed - original transaction is still active...
			doResumeSynchronization(suspendedSynchronizations);
			throw ex;
		}
	}
	else if (transaction != null) {
		// Transaction active but no synchronization active.
		Object suspendedResources = doSuspend(transaction);
		return new SuspendedResourcesHolder(suspendedResources);
	}
	else {
		// Neither transaction nor synchronization active.
		return null;
	}
}

/**
 * 呼叫TransactionSynchronization的suspend方法,並清空和返回當前執行緒中所有的TransactionSynchronization物件
 */
private List<TransactionSynchronization> doSuspendSynchronization() {
	// 從synchronizations(一個ThreadLocal)中拿到所設定的TransactionSynchronization物件
	List<TransactionSynchronization> suspendedSynchronizations =
			TransactionSynchronizationManager.getSynchronizations();

	// 呼叫TransactionSynchronization物件的suspend()
	for (TransactionSynchronization synchronization : suspendedSynchronizations) {
		synchronization.suspend();
	}

	// 清空synchronizations
	TransactionSynchronizationManager.clearSynchronization();

	// 把獲取到的TransactionSynchronization返回
	return suspendedSynchronizations;
}

之前存在事務的執行邏輯

/**
 * 之前存在事務的執行邏輯
 * 原始碼位置:org.springframework.transaction.support.AbstractPlatformTransactionManager.handleExistingTransaction(TransactionDefinition, Object, boolean)
 */
private TransactionStatus handleExistingTransaction(
		TransactionDefinition definition, Object transaction, boolean debugEnabled)
		throws TransactionException {

	// PROPAGATION_NEVER:以非事務方式進行,如果存在事務則丟擲異常
	if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
		throw new IllegalTransactionStateException(
				"Existing transaction found for transaction marked with propagation 'never'");
	}

	// PROPAGATION_NOT_SUPPORTED:以非事務方式執行,如果當前存在事務則將當前事務掛起
	if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
		if (debugEnabled) {
			logger.debug("Suspending current transaction");
		}
		// 把當前事務掛起,其中就會把資料庫連線物件從ThreadLocal中移除
		Object suspendedResources = suspend(transaction);
		boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
		return prepareTransactionStatus(
				definition, null, false, newSynchronization, debugEnabled, suspendedResources);
	}

	// PROPAGATION_REQUIRES_NEW:建立一個新的事務並掛起當前事務
	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 {
			return startTransaction(definition, transaction, debugEnabled, suspendedResources);
		}
		catch (RuntimeException | Error beginEx) {
			resumeAfterBeginException(transaction, suspendedResources, beginEx);
			throw beginEx;
		}
	}

	// PROPAGATION_NESTED:果當前存在事務,則在巢狀事務內執行。如果當前沒有事務,則建立一個事務。
	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,
			// through the SavepointManager API implemented by TransactionStatus.
			// Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
			DefaultTransactionStatus status =
					prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
			// 建立一個savepoint
			status.createAndHoldSavepoint();
			return status;
		}
		else {
			// Nested transaction through nested begin and commit/rollback calls.
			// Usually only for JTA: Spring synchronization might get activated here
			// in case of a pre-existing JTA transaction.
			return startTransaction(definition, transaction, debugEnabled, null);
		}
	}

	// Assumably 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");
			}
		}
	}

	// 如果依然是Propagation.REQUIRED
	boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
	return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}

事務的提交邏輯

/**
 * 事務的提交
 */
protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) {
	if (txInfo != null && txInfo.getTransactionStatus() != null) {
		if (logger.isTraceEnabled()) {
			logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");
		}
		txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
	}
}

/**
 * 事務提交的準備邏輯
 */
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;

	// 可以通過TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();來設定
	// 事務本來是可以要提交的,但是可以強制回滾。比如報錯後更有好的提示。
	if (defStatus.isLocalRollbackOnly()) {
		if (defStatus.isDebug()) {
			logger.debug("Transactional code has requested rollback");
		}
		processRollback(defStatus, false);
		return;
	}

	// 判斷此事務在之前是否設定了需要回滾,跟globalRollbackOnParticipationFailure有關
	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;
	}

	// 提交
	processCommit(defStatus);
}

/**
 * 提交外部邏輯
 */
private void processCommit(DefaultTransactionStatus status) throws TransactionException {
	try {
		boolean beforeCompletionInvoked = false;

		try {
			boolean unexpectedRollback = false;

			// 空方法,無任何子類的實現
			prepareForCommit(status);
			// 呼叫同步器提交前的邏輯(回滾的時候不呼叫這個)
			triggerBeforeCommit(status);
			// 呼叫同步器完成前的邏輯
			triggerBeforeCompletion(status);
			beforeCompletionInvoked = true;

			if (status.hasSavepoint()) {
				if (status.isDebug()) {
					logger.debug("Releasing transaction savepoint");
				}
				unexpectedRollback = status.isGlobalRollbackOnly();
				status.releaseHeldSavepoint();
			}
			// 新的事務,直接呼叫提交
			else if (status.isNewTransaction()) {
				if (status.isDebug()) {
					logger.debug("Initiating transaction commit");
				}
				unexpectedRollback = status.isGlobalRollbackOnly();
				// 呼叫提交方法
				doCommit(status);
			}
			else if (isFailEarlyOnGlobalRollbackOnly()) {
				unexpectedRollback = status.isGlobalRollbackOnly();
			}

			// Throw UnexpectedRollbackException if we have a global rollback-only
			// marker but still didn't get a corresponding exception from commit.
			if (unexpectedRollback) {
				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 | Error ex) {
			if (!beforeCompletionInvoked) {
				triggerBeforeCompletion(status);
			}
			doRollbackOnCommitException(status, ex);
			throw ex;
		}

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

/**
 * 提交的核心邏輯,直接呼叫Connection的提交方法
 */
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 translateException("JDBC commit", ex);
	}
}

/**
 * 恢復被掛起的資源到當前執行緒中
 */
private void cleanupAfterCompletion(DefaultTransactionStatus status) {
	status.setCompleted();
	if (status.isNewSynchronization()) {
		TransactionSynchronizationManager.clear();
	}
	// 判斷當前事務執行的方法,是不是建立這個事務的方法
	if (status.isNewTransaction()) {
		// 這裡會去關閉資料庫連線
		doCleanupAfterCompletion(status.getTransaction());
	}

	// 恢復被掛起的資源到當前執行緒中
	if (status.getSuspendedResources() != null) {
		if (status.isDebug()) {
			logger.debug("Resuming suspended transaction after completion of inner transaction");
		}
		Object transaction = (status.hasTransaction() ? status.getTransaction() : null);
		// 恢復
		resume(transaction, (SuspendedResourcesHolder) status.getSuspendedResources());
	}
}

回滾事務的邏輯

protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
	if (txInfo != null && txInfo.getTransactionStatus() != null) {
		if (logger.isTraceEnabled()) {
			logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
					"] after exception: " + ex);
		}

		// transactionAttribute的實現類為RuleBasedTransactionAttribute,父類為DefaultTransactionAttribute
		// 判斷配置的rollBackFor的異常資訊
		if (txInfo.transactionAttribute != null && 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 | Error ex2) {
				logger.error("Application exception overridden by rollback exception", ex);
				throw ex2;
			}
		}
		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 | Error ex2) {
				logger.error("Application exception overridden by commit exception", ex);
				throw ex2;
			}
		}
	}
}

/**
 * 判斷回滾條件是否滿足
 * 原始碼位置:org.springframework.transaction.interceptor.RuleBasedTransactionAttribute.rollbackOn(Throwable)
 */
public boolean rollbackOn(Throwable ex) {
	RollbackRuleAttribute winner = null;
	int deepest = Integer.MAX_VALUE;

	if (this.rollbackRules != null) {
		// 遍歷所有的RollbackRuleAttribute,判斷現在丟擲的異常ex是否匹配RollbackRuleAttribute中指定的異常型別的子類或本身
		for (RollbackRuleAttribute rule : this.rollbackRules) {
			int depth = rule.getDepth(ex);
			if (depth >= 0 && depth < deepest) {
				deepest = depth;
				winner = rule;
			}
		}
	}

	// User superclass behavior (rollback on unchecked) if no rule matches.
	// 沒有匹配的規則,呼叫父類判斷是不是執行時異常
	if (winner == null) {
		return super.rollbackOn(ex);
	}

	// ex所匹配的RollbackRuleAttribute,可能是NoRollbackRuleAttribute,如果是匹配的NoRollbackRuleAttribute,那就表示現在這個異常ex不用回滾
	return !(winner instanceof NoRollbackRuleAttribute);
}

/**
 * 回滾前的準備邏輯
 * 原始碼位置:org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(TransactionStatus)
 */
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, false);
}

/**
 * 回滾
 */
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
	try {
		boolean unexpectedRollback = unexpected;

		try {
			// 只會觸發完成前的同步器邏輯
			triggerBeforeCompletion(status);

			// 比如mysql中的savepoint
			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");
				}
				// 如果當前執行的方法是新開了一個事務,那麼就直接回滾
				doRollback(status);
			}
			else {
				// Participating in larger transaction
				// 如果當前執行的方法,是公用了一個已存在的事務,而當前執行的方法拋了異常,則要判斷整個事務到底要不要回滾,看具體配置
				if (status.hasTransaction()) {

					// 如果一個事務中有兩個方法,第二個方法拋異常了,那麼第二個方法就相當於執行失敗需要回滾,如果globalRollbackOnParticipationFailure為true,那麼第一個方法在沒有拋異常的情況下也要回滾
					if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
						if (status.isDebug()) {
							logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
						}
						// 直接將rollbackOnly設定到ConnectionHolder中去,表示整個事務的sql都要回滾
						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 early
				if (!isFailEarlyOnGlobalRollbackOnly()) {
					unexpectedRollback = false;
				}
			}
		}
		catch (RuntimeException | Error ex) {
			triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
			throw ex;
		}

		triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);

		// Raise UnexpectedRollbackException if we had a global rollback-only marker
		if (unexpectedRollback) {
			throw new UnexpectedRollbackException(
					"Transaction rolled back because it has been marked as rollback-only");
		}
	}
	finally {
		cleanupAfterCompletion(status);
	}
}

結束語

  • 獲取更多本文的前置知識文章,以及新的有價值的文章,讓我們一起成為架構師!
  • 關注公眾號,可以讓你對MySQL、併發程式設計、spring原始碼有深入的瞭解!
  • 關注公眾號,後續持續高效的學習JVM!
  • 這個公眾號,無廣告!!!每日更新!!!
    作者公眾號.jpg

相關文章