简体   繁体   English

在事务方法 spring 中运行没有事务的代码

[英]Run code without transaction in transactional mehod spring

I have service like this:我有这样的服务:

class ServiceImpl implements Service {
   @Override
   @Transactional
   public int method() {
      //some logic in transaction
      method2();//I want run this without transaction
      return 2;
   }

   @Override
   @Transactional(propagation = Propagation.REQUIRES_NEW)
   public void method2() {
     //external api call
   }
}

How can I run method2 without transaction or in new transaction?如何在没有事务或新事务的情况下运行 method2? Can I run in my controller class this 2 method like this:我可以在我的 controller class 中运行这两种方法吗:

service.method();
service.method2();

@Transactional is powered by Aspect-Oriented Programming. @Transactional 由面向方面的编程提供支持。 Therefore, processing occurs when a bean is called from another bean.因此,当从另一个 bean 调用一个 bean 时,就会发生处理。 You can resolve this problem by您可以通过以下方式解决此问题

  • self-inject自注入
class ServiceImpl implements Service {

   @Lazy private final Service self;
   @Override
   @Transactional
   public int method() {
      //some logic in transaction
      self.method2();//I want run this without transaction
      return 2;
   }

   @Override
   @Transactional(propagation = Propagation.REQUIRES_NEW)
   public void method2() {
     //external api call
   }
}

  • create another bean.创建另一个bean。
class ServiceImpl implements Service {

   private final ExternalService service;
   @Override
   @Transactional
   public int method() {
      //some logic in transaction
      method2();//I want run this without transaction
      return 2;
   }

   @Override
   public void method2() {
     service.method2();
   }
}

@Service
class ExternalService{

   @Transactional(propagation = Propagation.REQUIRES_NEW)
   public void method2() {
     //external api call
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM