Sobes.tech
Junior — Middle

Why does calling a private method marked with @Transactional annotation not lead to transaction execution?

sobes.tech AI

Answer from AI

The @Transactional annotation in Spring works through proxies that intercept method calls and manage transactions.

If a method annotated with @Transactional is declared as private, calling this method from within the same class occurs directly, without passing through the proxy. As a result, Spring does not 'see' the call and does not start a transaction.

For the transaction to work, the method must be public (or, in some cases, protected/package-private), and the call must go through the proxy (for example, a call from another bean or through self-injection).

Example:

@Service
public class MyService {

    @Transactional
    public void publicMethod() {
        privateMethod(); // call within the class, transaction will not start for privateMethod
    }

    @Transactional
    private void privateMethod() {
        // transaction will not work
    }
}

The solution is to make the method public and call it through the proxy so that the transaction is applied.

Why does calling a private method marked with… - sobes.tech