Skip to content
Advertisement

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? Can I run in my controller class this 2 method like this:

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

Advertisement

Answer

@Transactional is powered by Aspect-Oriented Programming. Therefore, processing occurs when a bean is called from another 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.
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
   }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement