事务注解 @Transactional失效的3种场景及解决办法

开发 后端
本文介绍了@Transactional 失效的3种场景及解决办法 ,一起来看看吧。

  [[393149]]

Transactional失效场景

第一种 Transactional注解标注方法修饰符为非public时,@Transactional注解将会不起作用。例如以下代码,定义一个错误的@Transactional标注实现,修饰一个默认访问符的方法: 

  1. /**  
  2.  * @author zhoujy  
  3.  **/  
  4. @Component  
  5. public class TestServiceImpl {  
  6.     @Resource  
  7.     TestMapper testMapper;   
  8.      @Transactional  
  9.     void insertTestWrongModifier() { 
  10.         int re = testMapper.insert(new Test(10,20,30));  
  11.         if (re > 0) {  
  12.             throw new NeedToInterceptException("need intercept");  
  13.         }  
  14.         testMapper.insert(new Test(210,20,30));  
  15.     }  

在同一个包内,新建调用对象,进行访问。 

  1. @Component  
  2. public class InvokcationService {  
  3.     @Resource  
  4.     private TestServiceImpl testService;  
  5.     public void invokeInsertTestWrongModifier(){  
  6.         //调用@Transactional标注的默认访问符方法  
  7.         testService.insertTestWrongModifier(); 
  8.      }  

测试用例: 

  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. public class DemoApplicationTests {  
  4.    @Resource  
  5.    InvokcationService invokcationService;  
  6.    @Test  
  7.    public void  testInvoke(){  
  8.       invokcationService.invokeInsertTestWrongModifier();  
  9.    }  

以上的访问方式,导致事务没开启,因此在方法抛出异常时,testMapper.insert(new Test(10,20,30));操作不会进行回滚。如果TestServiceImpl#insertTestWrongModifier方法改为public的话将会正常开启事务,testMapper.insert(new Test(10,20,30));将会进行回滚。

第二种失效场景

在类内部调用调用类内部@Transactional标注的方法,这种情况下也会导致事务不开启。示例代码如下,设置一个内部调用: 

  1. /**  
  2.  * @author zhoujy  
  3.  **/  
  4. @Component  
  5. public class TestServiceImpl implements TestService { 
  6.     @Resource  
  7.     TestMapper testMapper;  
  8.     @Transactional  
  9.     public void insertTestInnerInvoke() {  
  10.         //正常public修饰符的事务方法  
  11.         int re = testMapper.insert(new Test(10,20,30));  
  12.         if (re > 0) {  
  13.             throw new NeedToInterceptException("need intercept");  
  14.         }  
  15.         testMapper.insert(new Test(210,20,30));  
  16.     }  
  17.     public void testInnerInvoke(){  
  18.         //类内部调用@Transactional标注的方法。  
  19.         insertTestInnerInvoke();  
  20.     }  

测试用例: 

  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. public class DemoApplicationTests {  
  4.    @Resource  
  5.    TestServiceImpl testService;  
  6.    /**  
  7.     * 测试内部调用@Transactional标注方法  
  8.     */  
  9.    @Test  
  10.    public void  testInnerInvoke(){  
  11.        //测试外部调用事务方法是否正常  
  12.       //testService.insertTestInnerInvoke();  
  13.        //测试内部调用事务方法是否正常  
  14.       testService.testInnerInvoke();  
  15.    }  

上面就是使用的测试代码,运行测试知道,外部调用事务方法能够征程开启事务,testMapper.insert(new Test(10,20,30))操作将会被回滚;

然后运行另外一个测试用例,调用一个方法在类内部调用内部被@Transactional标注的事务方法,运行结果是事务不会正常开启,testMapper.insert(new Test(10,20,30))操作将会保存到数据库不会进行回滚。

第三种失效场景

事务方法内部捕捉了异常,没有抛出新的异常,导致事务操作不会进行回滚。示例代码如下。 

  1. /**  
  2.  * @author zhoujy  
  3.  **/  
  4. @Component  
  5. public class TestServiceImpl implements TestService {  
  6.     @Resource  
  7.     TestMapper testMapper;  
  8.     @Transactional  
  9.     public void insertTestCatchException() {  
  10.         try {  
  11.             int re = testMapper.insert(new Test(10,20,30));  
  12.             if (re > 0) {  
  13.                 //运行期间抛异常  
  14.                 throw new NeedToInterceptException("need intercept");  
  15.             }  
  16.             testMapper.insert(new Test(210,20,30));  
  17.         }catch (Exception e){  
  18.             System.out.println("i catch exception");  
  19.         }  
  20.     } 
  21.  

测试用例代码如下。 

  1. @RunWith(SpringRunner.class)  
  2. @SpringBootTest  
  3. public class DemoApplicationTests {  
  4.    @Resource  
  5.    TestServiceImpl testService;  
  6.    @Test  
  7.    public void testCatchException(){  
  8.       testService.insertTestCatchException();  
  9.    }  

运行测试用例发现,虽然抛出异常,但是异常被捕捉了,没有抛出到方法 外, testMapper.insert(new Test(210,20,30))操作并没有回滚。

以上三种就是@Transactional注解不起作用,@Transactional注解失效的主要原因。下面结合spring中对于@Transactional的注解实现源码分析为何导致@Transactional注解不起作用。

@Transactional注解不起作用原理分析

第一种场景分析

@Transactional注解标注方法修饰符为非public时,@Transactional注解将会不起作用。这里分析 的原因是,@Transactional是基于动态代理实现的,@Transactional注解实现原理中分析了实现方法,在bean初始化过程中,对含有@Transactional标注的bean实例创建代理对象,这里就存在一个spring扫描@Transactional注解信息的过程,不幸的是源码中体现,标注@Transactional的方法如果修饰符不是public,那么就默认方法的@Transactional信息为空,那么将不会对bean进行代理对象创建或者不会对方法进行代理调用

@Transactional注解实现原理中,介绍了如何判定一个bean是否创建代理对象,大概逻辑是。根据spring创建好一个aop切点BeanFactoryTransactionAttributeSourceAdvisor实例,遍历当前bean的class的方法对象,判断方法上面的注解信息是否包含@Transactional,如果bean任何一个方法包含@Transactional注解信息,那么就是适配这个BeanFactoryTransactionAttributeSourceAdvisor切点。则需要创建代理对象,然后代理逻辑为我们管理事务开闭逻辑。

spring源码中,在拦截bean的创建过程,寻找bean适配的切点时,运用到下面的方法,目的就是寻找方法上面的@Transactional信息,如果有,就表示切点BeanFactoryTransactionAttributeSourceAdvisor能够应用(canApply)到bean中,

AopUtils#canApply(org.springframework.aop.Pointcut, java.lang.Class<?>, boolean) 

  1. public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {  
  2.    Assert.notNull(pc, "Pointcut must not be null");  
  3.    if (!pc.getClassFilter().matches(targetClass)) {  
  4.       return false;  
  5.    }  
  6.    MethodMatcher methodMatcher = pc.getMethodMatcher();  
  7.    if (methodMatcher == MethodMatcher.TRUE) {  
  8.       // No need to iterate the methods if we're matching any method anyway...  
  9.       return true;  
  10.    }  
  11.    IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null 
  12.    if (methodMatcher instanceof IntroductionAwareMethodMatcher) {  
  13.       introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher; 
  14.    }  
  15.     //遍历class的方法对象  
  16.    Set<Class<?>> classes = new LinkedHashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));  
  17.    classes.add(targetClass);  
  18.    for (Class<?> clazz : classes) {  
  19.       Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);  
  20.       for (Method method : methods) {  
  21.          if ((introductionAwareMethodMatcher != null &&  
  22.                introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||  
  23.              //适配查询方法上的@Transactional注解信息    
  24.              methodMatcher.matches(method, targetClass)) {  
  25.             return true;  
  26.          }  
  27.       }  
  28.    }  
  29.    return false;  

我们可以在上面的方法打断点,一步一步调试跟踪代码,最终上面的代码还会调用如下方法来判断。在下面的方法上断点,回头看看方法调用堆栈也是不错的方式跟踪。

AbstractFallbackTransactionAttributeSource#getTransactionAttribute

  •  AbstractFallbackTransactionAttributeSource#computeTransactionAttribute 
  1. protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {  
  2.    // Don't allow no-public methods as required.  
  3.    //非public 方法,返回@Transactional信息一律是null  
  4.    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {  
  5.       return null;  
  6.    }  
  7.    //后面省略.......  
  8.  } 

不创建代理对象

所以,如果所有方法上的修饰符都是非public的时候,那么将不会创建代理对象。以一开始的测试代码为例,如果正常的修饰符的testService是下面图片中的,经过cglib创建的代理对象。

如果class中的方法都是非public的那么将不是代理对象。

不进行代理调用

考虑一种情况,如下面代码所示。两个方法都被@Transactional注解标注,但是一个有public修饰符一个没有,那么这种情况我们可以预见的话,一定会创建代理对象,因为至少有一个public修饰符的@Transactional注解标注方法。

创建了代理对象,insertTestWrongModifier就会开启事务吗?答案是不会。 

  1. /**  
  2.  * @author zhoujy  
  3.  **/  
  4. @Component  
  5. public class TestServiceImpl implements TestService {  
  6.     @Resource  
  7.     TestMapper testMapper;  
  8.     @Override  
  9.     @Transactional  
  10.     public void insertTest() {  
  11.         int re = testMapper.insert(new Test(10,20,30));  
  12.         if (re > 0) {  
  13.             throw new NeedToInterceptException("need intercept");  
  14.         }  
  15.         testMapper.insert(new Test(210,20,30));  
  16.     }    
  17.     @Transactional  
  18.     void insertTestWrongModifier() {  
  19.         int re = testMapper.insert(new Test(10,20,30));  
  20.         if (re > 0) {  
  21.             throw new NeedToInterceptException("need intercept");  
  22.         }  
  23.         testMapper.insert(new Test(210,20,30));  
  24.     }  

原因是在动态代理对象进行代理逻辑调用时,在cglib创建的代理对象的拦截函数中CglibAopProxy.DynamicAdvisedInterceptor#intercept,有一个逻辑如下,目的是获取当前被代理对象的当前需要执行的method适配的aop逻辑。

  1. List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); 

而针对@Transactional注解查找aop逻辑过程,相似地,也是执行一次

AbstractFallbackTransactionAttributeSource#getTransactionAttribute

  •  AbstractFallbackTransactionAttributeSource#computeTransactionAttribute

也就是说还需要找一个方法上的@Transactional注解信息,没有的话就不执行代理@Transactional对应的代理逻辑,直接执行方法。没有了@Transactional注解代理逻辑,就无法开启事务,这也是上一篇已经讲到的。

第二种场景分析

在类内部调用调用类内部@Transactional标注的方法。这种情况下也会导致事务不开启。

经过对第一种的详细分析,对这种情况为何不开启事务管理,原因应该也能猜到;

既然事务管理是基于动态代理对象的代理逻辑实现的,那么如果在类内部调用类内部的事务方法,这个调用事务方法的过程并不是通过代理对象来调用的,而是直接通过this对象来调用方法,绕过的代理对象,肯定就是没有代理逻辑了。

其实我们可以这样玩,内部调用也能实现开启事务,代码如下。 

  1. /**  
  2.  * @author zhoujy  
  3.  **/  
  4. @Component  
  5. public class TestServiceImpl implements TestService {  
  6.     @Resource 
  7.      TestMapper testMapper;  
  8.     @Resource  
  9.     TestServiceImpl testServiceImpl;  
  10.     @Transactional  
  11.     public void insertTestInnerInvoke() {  
  12.         int re = testMapper.insert(new Test(10,20,30));  
  13.         if (re > 0) {  
  14.             throw new NeedToInterceptException("need intercept");  
  15.         }  
  16.         testMapper.insert(new Test(210,20,30));  
  17.     }  
  18.     public void testInnerInvoke(){  
  19.         //内部调用事务方法 
  20.          testServiceImpl.insertTestInnerInvoke();  
  21.     }  

上面就是使用了代理对象进行事务调用,所以能够开启事务管理,但是实际操作中,没人会闲的蛋疼这样子玩~

第三种场景分析

事务方法内部捕捉了异常,没有抛出新的异常,导致事务操作不会进行回滚。

这种的话,可能我们比较常见,问题就出在代理逻辑中,我们先看看源码里卖弄动态代理逻辑是如何为我们管理事务的。

TransactionAspectSupport#invokeWithinTransaction

代码如下。 

  1. protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)  
  2.       throws Throwable {  
  3.    // If the transaction attribute is null, the method is non-transactional.  
  4.    final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);  
  5.    final PlatformTransactionManager tm = determineTransactionManager(txAttr); 
  6.    final String joinpointIdentification = methodIdentification(method, targetClass);  
  7.    if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {  
  8.       // Standard transaction demarcation with getTransaction and commit/rollback calls.  
  9.        //开启事务  
  10.       TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);  
  11.       Object retVal = null 
  12.       try {  
  13.          // This is an around advice: Invoke the next interceptor in the chain.  
  14.          // This will normally result in a target object being invoked. 
  15.           //反射调用业务方法  
  16.          retVal = invocation.proceedWithInvocation();  
  17.       }  
  18.       catch (Throwable ex) {  
  19.          // target invocation exception  
  20.           //异常时,在catch逻辑中回滚事务  
  21.          completeTransactionAfterThrowing(txInfo, ex);  
  22.          throw ex;  
  23.       }  
  24.       finally {  
  25.          cleanupTransactionInfo(txInfo);  
  26.       }  
  27.        //提交事务 
  28.        commitTransactionAfterReturning(txInfo);  
  29.       return retVal;  
  30.    }  
  31.    else {  
  32.      //....................  
  33.    }  

所以看了上面的代码就一目了然了,事务想要回滚,必须能够在这里捕捉到异常才行,如果异常中途被捕捉掉,那么事务将不会回滚。 

 

责任编辑:庞桂玉 来源: Hollis
相关推荐

2023-09-28 09:07:54

注解失效场景

2023-09-27 16:22:51

SpringMySQL原子性

2023-05-05 07:39:04

Spring事务面试

2020-04-14 13:32:56

@Transacti失效场景

2023-11-02 07:52:30

Java工具

2024-01-29 08:28:01

Spring事务失效

2019-08-29 14:29:42

JVM内存 Java

2021-09-04 07:56:44

Spring事务失效

2009-08-18 16:45:50

Tomcat内存溢出

2012-05-29 16:30:33

Tomcat内存溢出

2022-02-14 16:53:57

Spring项目数据库

2021-06-26 14:59:13

SpringTransaction执行

2022-09-20 22:27:08

事务失效public 修饰

2023-07-05 08:45:18

Spring事务失效场景

2015-03-09 15:41:08

MongoDB查询超时异常Socket Time

2020-06-02 09:57:51

Python数据技术

2022-09-14 19:50:22

事务场景流程

2012-05-30 16:19:11

2010-01-27 12:06:00

UPS常见故障

2009-07-27 13:38:10

服务器变慢 Ping
点赞
收藏

51CTO技术栈公众号