Sobes.tech
Senior

How to call a @Transactional method within the same service (self-invocation)?

sobes.tech AI

Answer from AI

Calling a @Transactional method within the same service (self-invocation) will not work if you simply call the method directly because Spring proxies do not intercept calls within the same object.

To work around this limitation, you can:

  1. Move the @Transactional method to a separate service and call it through the Spring bean.

  2. Within the current service, obtain a proxy of itself via ApplicationContext and call the method through the proxy:

@Service
public class MyService {

    @Autowired
    private ApplicationContext context;

    public void outerMethod() {
        // Get a proxy of itself
        MyService proxy = context.getBean(MyService.class);
        proxy.transactionalMethod();
    }

    @Transactional
    public void transactionalMethod() {
        // transactional code
    }
}
  1. Use AspectJ instead of proxies, then self-invocation will work, but this requires additional configuration.

Most often, the first option is recommended — splitting the logic into two beans.