Spring声明式事务注解之事务方法的执行

目录

1. 说明

2. 执行事务方法

3. 总结


1. 说明

事务方法执行,原理跟AOP是一样的,事务类被增强,然后执行事务方法的时候,其实是增强类执行目标方法和一个拦截器链,这里的拦截器是TransactionInterceptor,然后在拦截器TransactionInterceptor里面对目标方法进行事务管理;

2. 执行事务方法

  • 2.1 事务方法执行的调用链如下

  • 2.2 事务方法执行步骤

跟AOP原理一样,先后执行顺序如下:

》 com.yibai.spring.annotation.tx.service.PersonService.savePerson(Person) ;
》 org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor.intercept(Object, Method, Object[], MethodProxy)这里会根据增强器转换成拦截器,最后得到只有一个拦截器TransactionInterceptor的list集合的拦截器链;
》 创建CglibMethodInvocation,调用CglibMethodInvocation.proceed();
》 最后来到事务方法拦截器TransactionInterceptor的invoke方法中,完成目标类的事务管理;

  • 2.3 事务拦截关键方法分析        

       2.3.1 CglibAopProxy.DynamicAdvisedInterceptor.intercept(): 拦截事务方法的执行;

@Override
public Object proceed() throws Throwable {
	//	We start with an index of -1 and increment early.
	if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
		// 事务方法本身
		return invokeJoinpoint();
	}

	// 获取第一个拦截件TransactionInterceptor
	Object interceptorOrInterceptionAdvice =
			this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
	if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
		// Evaluate dynamic method matcher here: static part will already have
		// been evaluated and found to match.
		InterceptorAndDynamicMethodMatcher dm =
				(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
		if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
			return dm.interceptor.invoke(this);
		}
		else {
			// Dynamic matching failed.
			// Skip this interceptor and invoke the next in the chain.
			return proceed();
		}
	}
	else {
		// It's an interceptor, so we just invoke it: The pointcut will have
		// been evaluated statically before this object was constructed.
		// 执行TransactionInterceptor的invoke方法;
		return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
	}
}

       2.3.2  事务拦截器TransactionInterceptor中的invoke(): 完成目标类的事务管理;

@Override
public Object invoke(final 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 InvocationCallback() {
		@Override
		public Object proceedWithInvocation() throws Throwable {
			return invocation.proceed();
		}
	});
}

其中invokeWithinTransaction()方法的实现如下:

protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
		throws Throwable {

	// If the transaction attribute is null, the method is non-transactional.
	// 从AnnotationTransactionAttributeSource中获取事务信息(在解析事务类的时候已经被解析,这里只是从缓存中获取)
	final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
		
	// 根据事务信息txAttr获取事务管理器,返回DataSourceTransactionManager
	final PlatformTransactionManager tm = determineTransactionManager(txAttr);
	final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

	if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
		// 标准事务
		// Standard transaction demarcation with getTransaction and commit/rollback calls.
		// 创建事务TransactionInfo并开启
		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.
			// 调用目标方法
			retVal = invocation.proceedWithInvocation();
		}
		catch (Throwable ex) {
			// target invocation exception
			// 如果异常则回滚事务
			completeTransactionAfterThrowing(txInfo, ex);
			throw ex;
		}
		finally {
			// 清楚该事务信息
			cleanupTransactionInfo(txInfo);
		}
		// 如果成功则提交事务
		commitTransactionAfterReturning(txInfo);
		return retVal;
	}

	else {
		// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
		// 如果事务管理器是CallbackPreferringPlatformTransactionManager则走这里
		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();
		}
	}
}

所以是在拦截器TransactionInterceptor的invoke方法中完成目标方法的事务管理;

3. 总结

事务方法执行,原理就是增强类执行事务方法和拦截器TransactionInterceptor,其中在TransactionInterceptor完成对事务方法的事务管理;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章