Spring Boot & Microservices (50 Qs)•Part 3: Microservices, Distributed Systems & Observability (25 - 35)
`@Transactional` Internals: The Self-Invocation Anti-Pattern.
senior LevelCode ExampleSystem DesignDatabases & SQLMicroservices
In Simple Words: Spring manages transactions using AOP dynamic proxies:
- The Self-Invocation Trap: If
MethodA()callsthis.MethodB()within the same class, andMethodB()is annotated with@Transactional, the transaction is completely ignored! Why? Becausethisbypasses the Spring AOP proxy wrapper and invokes the raw target method directly! - Rollback Rule: By default, Spring only rolls back for unchecked exceptions (
RuntimeException,Error). To roll back on checked exceptions, you must explicitly specify:@Transactional(rollbackFor = Exception.class)
java
@Service
public class OrderService {
// ❌ Anti-pattern: Internal call bypasses proxy!
public void processOrder() {
this.saveOrder(); // @Transactional on saveOrder is NOT executed!
}
@Transactional(rollbackFor = Exception.class)
public void saveOrder() { /* ... */ }
}