前面我们对Spring事务框架以及Spring启用事务管理的@EnableTransactionManagement进行了学习,了解了Spring事务管理的底层工作机制。
有关Spring事务管理剩余尚未学习研究的还有事务如何生效、以及事务生效后具体的AOP切入和增强过程。
我们先研究事务生效后具体的AOP切入和增强过程。
基于Cglib实现的AOP增强都是通过拦截器Interceptor实现的,通过前面几篇文章的分析,我们知道Spring事务的拦截器是TransactionInteceptor,我们直接从拦截器的invoke方法入手。
TransactionInteceptor#invoke
看一下TransactionInterceptor的类结构:
AOP Alliance MethodInterceptor for declarative transaction management using the common Spring transaction infrastructure (PlatformTransactionManager/ org.springframework.transaction.ReactiveTransactionManager).
Derives from the TransactionAspectSupport class which contains the integration with Spring's underlying transaction API. TransactionInterceptor simply calls the relevant superclass methods such as invokeWithinTransaction in the correct order.AOP联盟的方法拦截器,用于实现基于Spring事务框架的事务管理功能。
继承自集成了Spring底层事务管理API的TransactionAspectSupport类。
所以通过JavaDoc我们知道TransactionIntecepor是Spring事务管理中的方法拦截器,他有一个父类叫TransactionAspectSupport。
开始分析他的invoke方法。
首先获取到targetClass,targetClass其实就是被@Transactional注解的业务类,通过参数invocation传进来。
@Override
@Nullable
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);
然后调用invokeWithinTransaction方法,该方法在TransactionAspectSupport类实现,我们稍后分析。
// Adapt to TransactionAspectSupport's invokeWithinTransaction...
return invokeWithinTransaction(invocation.getMethod(), targetClass, new CoroutinesInvocationCallback() {
@Override
@Nullable
public Object proceedWithInvocation() throws Throwable {
return invocation.proceed();
}
@Override
public Object getTarget() {
return invocation.getThis();
}
@Override
public Object[] getArguments() {
return invocation.getArguments();
}
});