开发者

Spring事务中@Transactional注解不生效的原因分析与解决

目录
  • 1. 引言
  • 2. 事务自调用问题重现
    • 2.1 示例代码
    • 2.2 问题现象
  • 3. 为什么事务自调用会失效
    • 3.1 Spring事务的代理机制编程
    • 3.2 自调用绕过代理
  • 4. 解决方案
    • 4.1 方法1:拆分到不同类(推荐)
    • 4.2 方法2:使用 AopContext.currentProxy()
    • 4.3 方法3:在调用方法上添加 @Transactional
    • 4.4 方法4:使用编程式事务
  • 5. 最佳实践
    • 6. 总结

      1. 引言

      在Spring框架中,@Transactional注解是管理数据库事务的核心方式。然而,许多开发者在使用时会遇到一个常见问题:在同一个类中,一个方法调用另一个带有@Transactional注解的方法时,事务并未生效。这种现象被称为事务自调用失效。

      本文将深入分析事务自调用的底层原理,解释为什么事务不生效,并提供多种解决方案,帮助开发者正确使用Spring事务管理。

      2. 事务自调用问题重现

      2.1 示例代码

      @Service
      public class OrderService {
      
          public void placeOrder(Order order) {
              checkInventory(order);       // 检查库存(非事务)
              deductInventory(order);      // 扣减库存(事务方法)
              createOrder(order);          // 创建订单(非事务)
          }
      
          @Transactional
          public void deductInventory(Order order) {
              inventoryRepository.reduceStock(order.getProductId(), order.getQuantity());
          }
      }
      

      在这个例子中:

      placeOrder() 是一个业务方法,调用了 deductInventory()。

      deductInventory() 被标记为 @Transactional,期望在扣减库存时开启事务。

      2.2 问题现象

      当 placeOrder() 调用 deductInventory() 时,事务并未生效。如果python deductInventory() 抛出异常,数据库操作不会回滚。

      3. 为什么事务自调用会失效

      3.1www.devze.com Spring事务的代理机制

      Spring的事务管理是基于AOP(面向切面编程)实现的,具体来说:

      • 代理模式:Spring会为带有@Transactional的类生成一个代理对象(JDK动态代理或CGLIB代理)。
      • 拦截器:代理对象会在目标方法执行前后添加事务管理逻辑(如开启事务、提交或回滚)。

      3.2 自调用绕过代理

      public void placeOrder(Order order) {
          this.deductInventory(order);  // 直接调用,不走代理
      }
      

      当 placeOrder() 调用 deductInventory() 时,它使用的是 this(即当前对象),而不是Spring生成的代理对象。

      因此,事务拦截器没有被触发,事务自然也不会生效。

      4. 解决方案

      4.1 方法1:拆分到不同类(推荐)

      将事务方法移到另一个Service,确保调用通过代理进行:

      @Service
      public class OrderService {
      
          @Autowired
          private InventoryService inventoryService;
      
          public void placeOrder(Order order) {
              checkInventory(order);
              inventoryService.deductInventory(order);  // 通过代理调用
              createOrder(order);
          }
      }
      
      @Service
      public class InventoryService {
      
          @Transactional
          public void deductInventory(Order order) {
              inventoryRepository.reduceStock(order.getProductId(), order.getQuantity());
          }
      }
      

      优点:

      • 符合单一职责原则(SRP)。
      • 事务管理清晰,不会出现自调用问题。

      4.2 方法2:使用 AopContext.currentProxy()

      如果http://www.devze.com必须自调用,可以获取当前代理对象:

      @Service
      public class OrderService {
      
          public void placeOrder(Order order) {
              checkInventory(order);
              ((OrderService) AopContext.currentProxy()).deductInventory(order);  // 通过代理调用
              createOrder(order);
          }
      
          @Transactional
          public void deductInventory(Order order) {
              inventoryRepository.reduceStock(order.getProductId(), order.getQuantity());
          }
      }
      

      注意:

      需要开启 @EnableASPectJAutoProxy(exposeProxy = true):

      @SpringBootApplication
      @EnableAspectJAutoProxy(exposeProxy = true)
      public class MyApp {
          public static void main(String[] args) {
              SpringApplication.run(MyApp.class, args);
          }
      }
      

      缺点:

      依赖Spring AOP机制,代码侵入性强。

      4.3 方法3:在调用方法上添加 @Transactional

      如果整个流程需要事务管理,可以直接在 placeOrder() 上添加 @Transactional:

      @Service
      public class OrderService {
      
          @Transactional
          public void placeOrder(Order order) {
              checkInventory(order);
              deductInventory(order);  // 即使自调用,外层事务仍生效
              createOrder(order);
          }
      
          public void deductInventory(Order order) {
              inventoryRepository.reduceStock(order.getProductId(), order.getQuantity());
          }
      }
      

      适用场景:

      整个方法需要事务管理,而javascript不是单个操作。

      4.4 方法4:使用编程式事务

      如果无法拆分类或修改代理设置,可以使用 TransactionTemplate:

      @Service
      public class OrderService {
      
          @Autowired
          private TransactionTemplate transactionTemplate;
      
          public void placeOrder(Order order) {
              checkInventory(order);
              transactionTemplate.execute(status -> {
                  deductInventory(order);  // 在事务内执行
                  return null;
              });
              createOrder(order);
          }
      
          public void deductInventory(Order order) {
              inventoryRepository.reduceStock(order.getProductId(), order.getQuantity());
          }
      }
      

      优点:

      更灵活,可以手动控制事务边界。

      5. 最佳实践

      避免自调用:尽量将事务方法拆分到不同的类。

      合理使用事务:不要在事务方法中执行耗时操作(如HTTP请求、IO操作)。

      事务传播机制:理解 @Transactional(propagation = Propagation.REQUIRED) 等选项。

      异常处理:确保异常能触发回滚(默认仅回滚 RuntimeException)。

      6. 总结

      方案适用场景优点缺点
      拆分到不同类推荐方案符合SRP,事务清晰需要额外类
      AopContext.currentProxy()必须自调用时可解决自调用问题侵入性强
      外层方法加 @Transactional整个流程需要事务简单直接事务范围扩大
      编程式事务需要精细控制灵活代码冗余

      关键结论:

      • Spring事务基于代理,自调用会绕过代理,导致事务失效。
      • 最佳方案是拆分事务方法到不同类,避免自调用问题。

      到此这篇关于Spring事务中@Transactional注解不生效的原因分析与解决的文章就介绍到这了,更多相关Spring @Transactional注解不生效内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

      0

      上一篇:

      下一篇:

      精彩评论

      暂无评论...
      验证码 换一张
      取 消

      最新开发

      开发排行榜