Spring Boot & Microservices (50 Qs)•Part 1: Spring Core, Auto-Configuration & Architecture (1 - 10)
How does Spring AOP work, and how does `@Transactional` leverage dynamic proxies?
senior LevelMost AskedSystem DesignDatabases & SQL
In Simple Words:
Spring AOP (Aspect-Oriented Programming) intercepts method execution using Dynamic Proxies (CGLIB class-based or JDK dynamic interface-based).
When a class has @Transactional:
- Spring generates a proxy wrapper around the target bean.
- The caller invokes the proxy's method.
- The proxy opens a database transaction (
connection.setAutoCommit(false)). - The proxy executes your method inside a
try-catchblock. - If successful, it commits (
connection.commit()). If aRuntimeExceptionoccurs, it rolls back (connection.rollback()). - Gotcha: Calling an
@Transactionalmethod internally from within the same class bypasses the proxy, meaning transaction management will NOT run.