Spring-Tx 事物源码解析

133 阅读1分钟

示例代码

@Transactional
@Service
public class DemoUserServiceImpl implements DemoUserService {

    @Autowired
    private DemoUserMapper demoUserMapper;

    @Override
    public void addDemoUser(DemoUser demoUser) {
            demoUserMapper.insert(demoUser);
            int i = 1 / 0;
    }
}

@Test
public void test() {
    demoUserService.addDemoUser(DemoUser.builder()
            .name("事物测试11111").age(100)
            .build());
}

Spring-tx 是如何 创建事物 提交事物 事物回滚?源码解读

1 CglibAopProxy 统一AOP控制方法 Intercept()

/**
 * General purpose AOP callback. Used when the target is dynamic or when the
 * proxy is not frozen.
 */

1.png

1.1. 跟踪方法源码
// We need to create a method invocation
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
ReflectiveMethodInvocation 
// We start with an index of -1 and increment early.
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
   return invokeJoinpoint();
}
这串代码 简单理解就是使拦截器 顺序执行 如事物 步骤 1 创建事物控制器 2 方法执行 3 事物回滚/提交 
下一步 如图 则是进入事物控制器内

2.png

2.1
继续源码追踪

TransactionInterceptor 3.png

3 真正事物源码

TransactionAspectSupport.invokeWithinTransaction()事物执行控制

4.png

3.1 目标方法执行的设计模式 

5.png 3.2 继续追踪源码

completeTransactionAfterThrowing(txInfo, ex);事物的回滚
DataSourceTransactionManager

6.png

4 end


[更多访问杨少的gitHUb](https://github.com/yanghui-git/MyCodeLoad3.0/)