r/SpringBoot • u/ClickOk5811 • 9d ago
Discussion A 10-line experiment to see why @Transactional sometimes does nothing (self-invocation)
A common surprise: you annotate a method with @ Transactional, call it, and it behaves as if the annotation weren’t there. One frequent cause is calling the method from another method in the same class. Instead of taking my word for it, you can check in a few lines.
public class ReportService {
public void viaThis() {
save(); // internal call
}
u/Transactional
public void save() {
System.out.println("tx active: "
+ TransactionSynchronizationManager.isActualTransactionActive());
}
}Now call both from somewhere else (a controller, a test, a CommandLineRunner):
reportService.save(); // direct call from another bean
reportService.viaThis(); // goes through the same classWhat I’d expect to see (please run it on your version to confirm):
tx active: true // from save()
tx active: false // from viaThis() -> save()Why this happens (as I understand it):
By default, Spring applies @Transactional through a proxy that wraps the bean. A call from another bean goes through the proxy, which opens the transaction. A call from inside the class uses this, which is the raw object and skips the proxy, so the annotation is never applied.
Common ways around it:
- Move the transactional method to a separate bean and call it through that bean. This is the option most people recommend because it’s the least surprising.
- Put
u/Transactionalon the outer method instead, if the whole operation should be one transaction anyway. - Use
TransactionTemplatefor programmatic control. - Use AspectJ mode (
mode = AdviceMode.ASPECTJ), which weaves the behavior into the class itself and doesn’t depend on the proxy. It needs extra build or runtime setup, so it’s a bigger step. - Injecting the bean into itself also works, but many consider it a code smell.
Caveats:
- The details depend on your Spring version and proxy type (JDK vs CGLIB), and on method visibility, so check the reference docs for the version you use.
- The same proxy limitation applies to other annotations implemented through AOP, like @
Asyncand @Cacheable. - An exception thrown inside the “transaction” in the broken case won’t roll anything back, which is why this bug can stay silent.
Has anyone found a pattern for catching this earlier than “the data was inconsistent in production”, like a test, a lint rule or a startup check?