Sobes.tech
Middle

What will happen if a method annotated with @Transactional is called within a method?

sobes.tech AI

Answer from AI

If a method marked with @Transactional is called from within the same object (Self-Invocation), a transaction will not be created or joined to an existing one. This happens because Spring AOP by default uses proxy objects to apply aspects, including transactions. When calling a method within the same object, the call goes directly to the real object (this), bypassing the proxy.

To ensure the transaction is applied in this case, you can use:

  • Self-bean injection:
// Assuming the class Foo is a Spring bean
@Service
public class Foo {

    @Autowired
    private Foo self; // Injecting the proxy object

    public void outerMethod() {
        // Calling the test() method on the proxy object
        self.test();
    }

    @Transactional
    public void test() {
        // This method will run within a transaction
    }
}
  • AopContext.currentProxy():
// Assuming the class Foo is a Spring bean
@Service
public class Foo {

    public void outerMethod() {
        // Calling the test() method on the proxy object via AopContext
        ((Foo) AopContext.currentProxy()).test();
    }

    @Transactional
    public void test() {
        // This method will run within a transaction
    }
}

If a method with @Transactional is called from another Spring bean, a transaction will be created or joined to an existing one, since the call will go through the proxy.