Understanding Spring Transaction Management and Its Core Concepts
This article explains how Spring manages transactions, detailing the three essential elements, annotation configuration, rollback rules, propagation behaviors, isolation levels, and the underlying AOP mechanism that enables declarative transaction handling in Java backend applications.
Relationship between Spring and Transactions Spring itself is not a transactional resource, but it can manage transactional resources such as relational databases and message queues, acting as a manager that controls transaction boundaries.
Three Essential Elements of Spring Transactions 1. DataSource : the actual transactional resource (e.g., MySQL). 2. Transaction Manager : a global caretaker that opens, commits, or rolls back transactions. 3. Transaction Attributes : configuration that marks which methods participate in a transaction and defines properties like isolation level and timeout.
Annotation‑Based Configuration Register a DataSource (e.g., DruidDataSource ) as a @Bean in the Spring container, enable transaction management with @EnableTransactionManagement on a @Configuration class, and annotate target classes or methods with @Transactional , optionally setting its attributes.
Nature of the @Transactional Annotation The annotation only provides metadata; at runtime the transaction infrastructure reads this metadata to configure bean behavior, indicating that a method should participate in a transaction and specifying related properties.
Declarative Transaction Implementation Spring AOP creates a transaction interceptor that surrounds method execution with transaction‑related advice, allowing the transaction to start before the method runs and to commit or roll back afterward.
How a Transaction Is Rolled Back If an unchecked exception propagates out of a transactional method, the transaction infrastructure catches it and decides whether to mark the transaction for rollback.
Default Rollback Rules Only RuntimeException and Error trigger a rollback by default; checked exceptions do not.
Configuring Rollback Exceptions Use rollbackFor / rollbackForClassName to specify checked exceptions that should cause a rollback, and noRollbackFor / noRollbackForClassName to exclude certain exceptions from causing a rollback.
Placement of @Transactional The annotation can be placed on a class (applies to all its methods) or on individual methods (method‑level settings override class‑level). It can also be placed on interfaces, but this requires JDK dynamic proxies; Spring recommends annotating the concrete class instead.
Proxy Limitation and Public Methods When using proxy‑based AOP, only public methods are intercepted. Protected, private, or package‑private methods will not trigger transaction behavior unless AspectJ weaving is used.
Self‑Invocation Issue Calls from one method of a bean to another method of the same bean bypass the proxy, so the second method’s transaction annotations are ignored. AspectJ weaving can solve this by applying transactions directly to the bytecode.
Transaction and Thread Association Spring binds a transaction to the current thread via a ThreadLocal<Map<Object, Object>> , where the key is the DataSource and the value is the underlying Connection .
Logical vs. Physical Transactions The physical transaction is the actual resource‑level transaction (e.g., a JDBC connection). Spring creates a logical transaction scope for each @Transactional method, which may be nested inside other logical transactions. Outer and inner logical transactions can have independent rollback decisions.
Propagation Behaviors Spring defines seven propagation types: REQUIRED , SUPPORTS , MANDATORY , REQUIRES_NEW , NOT_SUPPORTED , NEVER , and NESTED . Each determines how a method joins or creates a transaction.
Details of Common Propagation Types - REQUIRED : Join an existing transaction or create a new one if none exists. - REQUIRES_NEW : Always start a new physical transaction, suspending any existing one. - NESTED : Use savepoints within the same physical transaction to allow partial rollbacks. - SUPPORTS : Execute within a transaction if one exists; otherwise run non‑transactionally. - NOT_SUPPORTED : Suspend any existing transaction and run non‑transactionally. - MANDATORY : Must run within an existing transaction; otherwise throw an exception. - NEVER : Must not run within a transaction; throws an exception if a transaction is present.
Isolation Levels and Phenomena Supported isolation levels: DEFAULT , READ_UNCOMMITTED , READ_COMMITTED , REPEATABLE_READ , SERIALIZABLE . - Dirty read : Transaction reads uncommitted changes. - Non‑repeatable read : Same row yields different values in the same transaction. - Phantom read : New rows appear in a range query after another transaction inserts them.
Mnemonic for Isolation Phenomena Write‑Read = dirty read; Read‑Write‑Read = non‑repeatable read; WHERE INSERT WHERE = phantom read. MySQL’s default is REPEATABLE_READ .
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.