@EnableTransactionManagement注解注入了两个bean:

  1. AutoProxyRegistrar
  2. ProxyTransactionManagementConfiguration

AutoProxyRegistrar

AutoProxyRegistrar主要的作用就是注册了一个InfrastructureAdvisorAutoProxyCreator的Bean。
而InfrastructureAdvisorAutoProxyCreator继承了AbstractAdvisorAutoProxyCreator,所以这个类的主要作用就是开启自动代理的作用。

ProxyTransactionManagementConfiguration

ProxyTransactionManagementConfiguration中定义了三个bean:

  1. BeanFactoryTransactionAttributeSourceAdvisor:一个PointcutAdvisor
  2. AnnotationTransactionAttributeSource:就是Pointcut
  3. TransactionInterceptor:就是代理逻辑Advice
  1. BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
  2. advisor.setTransactionAttributeSource(transactionAttributeSource);
  3. advisor.setAdvice(transactionInterceptor);

BeanFactoryTransactionAttributeSourceAdvisor是一个Advisor,在构造BeanFactoryTransactionAttributeSourceAdvisor这个bean时,需要另外两Bean。

BeanFactoryTransactionAttributeSourceAdvisor中是这么定义PointCut的:

  1. private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
  2. @Override
  3. @Nullable
  4. protected TransactionAttributeSource getTransactionAttributeSource() {
  5. return transactionAttributeSource;
  6. }
  7. };

构造了一个PointCut, TransactionAttributeSource的实现对象为AnnotationTransactionAttributeSource,在PointCut匹配类时,会利用AnnotationTransactionAttributeSource去检查类上是否有@Transactional注解,在PointCut匹配方法时,会利用AnnotationTransactionAttributeSource去检查方法上是否有@Transactional注解。

所以ProxyTransactionManagementConfiguration的作用就是向Spring容器中添加了一个Advisor,有了Advisor,那么Spring在构造bean时就会查看当前bean是不是匹配所设置的PointCut(也就是beanClass上是否有@Transactional注解或beanClass中某个方法上是否有@Transactional注解),如果匹配,则利用所设置的Advise(也就是TransactionInterceptor)进行AOP,生成代理对象。

TransactionInterceptor

  1. public Object invoke(MethodInvocation invocation) throws Throwable {
  2. // Work out the target class: may be {@code null}.
  3. // The TransactionAttributeSource should be passed the target class
  4. // as well as the method, which may be from an interface.
  5. Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
  6. // Adapt to TransactionAspectSupport's invokeWithinTransaction...
  7. return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
  8. }
  1. @Nullable
  2. protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
  3. final InvocationCallback invocation) throws Throwable {
  4. // If the transaction attribute is null, the method is non-transactional.
  5. TransactionAttributeSource tas = getTransactionAttributeSource();
  6. final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
  7. final TransactionManager tm = determineTransactionManager(txAttr);
  8. if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
  9. ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
  10. if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) {
  11. throw new TransactionUsageException(
  12. "Unsupported annotated transaction on suspending function detected: " + method +
  13. ". Use TransactionalOperator.transactional extensions instead.");
  14. }
  15. ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType());
  16. if (adapter == null) {
  17. throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
  18. method.getReturnType());
  19. }
  20. return new ReactiveTransactionSupport(adapter);
  21. });
  22. return txSupport.invokeWithinTransaction(
  23. method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm);
  24. }
  25. PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
  26. final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
  27. if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
  28. // Standard transaction demarcation with getTransaction and commit/rollback calls.
  29. //开启事务
  30. TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
  31. Object retVal;
  32. try {
  33. // This is an around advice: Invoke the next interceptor in the chain.
  34. // This will normally result in a target object being invoked.
  35. //执行业务逻辑
  36. retVal = invocation.proceedWithInvocation();
  37. }
  38. catch (Throwable ex) {
  39. // target invocation exception
  40. //异常回滚
  41. completeTransactionAfterThrowing(txInfo, ex);
  42. throw ex;
  43. }
  44. finally {
  45. cleanupTransactionInfo(txInfo);
  46. }
  47. if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
  48. // Set rollback-only in case of Vavr failure matching our rollback rules...
  49. TransactionStatus status = txInfo.getTransactionStatus();
  50. if (status != null && txAttr != null) {
  51. retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
  52. }
  53. }
  54. commitTransactionAfterReturning(txInfo);
  55. return retVal;
  56. }
  57. else {
  58. Object result;
  59. final ThrowableHolder throwableHolder = new ThrowableHolder();
  60. // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
  61. try {
  62. result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
  63. TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
  64. try {
  65. Object retVal = invocation.proceedWithInvocation();
  66. if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
  67. // Set rollback-only in case of Vavr failure matching our rollback rules...
  68. retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
  69. }
  70. return retVal;
  71. }
  72. catch (Throwable ex) {
  73. if (txAttr.rollbackOn(ex)) {
  74. // A RuntimeException: will lead to a rollback.
  75. if (ex instanceof RuntimeException) {
  76. throw (RuntimeException) ex;
  77. }
  78. else {
  79. throw new ThrowableHolderException(ex);
  80. }
  81. }
  82. else {
  83. // A normal return value: will lead to a commit.
  84. throwableHolder.throwable = ex;
  85. return null;
  86. }
  87. }
  88. finally {
  89. cleanupTransactionInfo(txInfo);
  90. }
  91. });
  92. }
  93. catch (ThrowableHolderException ex) {
  94. throw ex.getCause();
  95. }
  96. catch (TransactionSystemException ex2) {
  97. if (throwableHolder.throwable != null) {
  98. logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
  99. ex2.initApplicationException(throwableHolder.throwable);
  100. }
  101. throw ex2;
  102. }
  103. catch (Throwable ex2) {
  104. if (throwableHolder.throwable != null) {
  105. logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
  106. }
  107. throw ex2;
  108. }
  109. // Check result state: It might indicate a Throwable to rethrow.
  110. if (throwableHolder.throwable != null) {
  111. throw throwableHolder.throwable;
  112. }
  113. return result;
  114. }
  115. }

TransactionInterceptor执行流程

Spring事务的底层实现流程.png

简单版流程

  1. 生成test事务状态对象
  2. test事务doBegin,获取并将数据库连接2825设置到test事务状态对象中
  3. 把test事务信息设置到事务同步管理器中
  4. 执行test业务逻辑方法(可以获取到test事务的信息)
    1. 生成a事务状态对象,并且可以获取到当前线程中已经存在的数据库连接2825
    2. 判断出来当前线程中已经存在事务
    3. 如果需要新开始事务,就先挂起数据库连接2825,挂起就是把test事务信息从事务同步管理器中转移到挂起资源对象中,并把当前a事务状态对象中的数据库连接设置为null
    4. a事务doBegin,新生成一个数据库连接2826,并设置到a事务状态对象中
    5. 把a事务信息设置到事务同步管理器中
    6. 执行a业务逻辑方法(可以利用事务同步管理器获取到a事务信息)
    7. 利用a事务状态对象,执行提交
    8. 提交之后会恢复所挂起的test事务,这里的恢复,其实只是把挂起资源对象中所保存的信息再转移回事务同步管理器中
  5. 继续执行test业务逻辑方法(仍然可以获取到test事务的信息)
  6. 利用test事务状态对象,执行提交

传播机制

Spring事务 - 图2

举例子

情况1

  1. @Component
  2. public class UserService {
  3. @Autowired
  4. private UserService userService;
  5. @Transactional
  6. public void test() {
  7. // test方法中的sql
  8. userService.a();
  9. }
  10. @Transactional
  11. public void a() {
  12. // a方法中的sql
  13. }
  14. }

默认情况下传播机制为REQUIRED

所以上面这种情况的执行流程如下:

  1. 新建一个数据库连接conn
  2. 设置conn的autocommit为false
  3. 执行test方法中的sql
  4. 执行a方法中的sql
  5. 执行conn的commit()方法进行提交

情况2

假如是这种情况

  1. @Component
  2. public class UserService {
  3. @Autowired
  4. private UserService userService;
  5. @Transactional
  6. public void test() {
  7. // test方法中的sql
  8. userService.a();
  9. int result = 100/0;
  10. }
  11. @Transactional
  12. public void a() {
  13. // a方法中的sql
  14. }
  15. }

所以上面这种情况的执行流程如下:

  1. 新建一个数据库连接conn
  2. 设置conn的autocommit为false
  3. 执行test方法中的sql
  4. 执行a方法中的sql
  5. 抛出异常
  6. 执行conn的rollback()方法进行回滚

情况3

假如是这种情况:

  1. @Component
  2. public class UserService {
  3. @Autowired
  4. private UserService userService;
  5. @Transactional
  6. public void test() {
  7. // test方法中的sql
  8. userService.a();
  9. }
  10. @Transactional
  11. public void a() {
  12. // a方法中的sql
  13. int result = 100/0;
  14. }
  15. }

所以上面这种情况的执行流程如下:

  1. 新建一个数据库连接conn
  2. 设置conn的autocommit为false
  3. 执行test方法中的sql
  4. 执行a方法中的sql
  5. 抛出异常
  6. 执行conn的rollback()方法进行回滚

情况4

如果是这种情况:

  1. @Component
  2. public class UserService {
  3. @Autowired
  4. private UserService userService;
  5. @Transactional
  6. public void test() {
  7. // test方法中的sql
  8. userService.a();
  9. }
  10. @Transactional(propagation = Propagation.REQUIRES_NEW)
  11. public void a() {
  12. // a方法中的sql
  13. int result = 100/0;
  14. }
  15. }

所以上面这种情况的执行流程如下:

  1. 新建一个数据库连接conn
  2. 设置conn的autocommit为false
  3. 执行test方法中的sql
  4. 又新建一个数据库连接conn2
  5. 执行a方法中的sql
  6. 抛出异常
  7. 执行conn2的rollback()方法进行回滚
  8. 继续抛异常
  9. 执行conn的rollback()方法进行回滚