Backend Development 13 min read

Understanding Spring Transaction Management: @EnableTransactionManagement, Execution Flow, Propagation, and Forced Rollback

This article explains how Spring enables transaction management through @EnableTransactionManagement, details the underlying advisor and proxy mechanisms, describes the basic and detailed execution steps, explores propagation types with practical code examples, and shows how to force rollbacks and use TransactionSynchronization for lifecycle callbacks.

Top Architect
Top Architect
Top Architect
Understanding Spring Transaction Management: @EnableTransactionManagement, Execution Flow, Propagation, and Forced Rollback

Spring transaction management is activated by adding the @EnableTransactionManagement annotation, which registers two essential beans: AutoProxyRegistrar and ProxyTransactionManagementConfiguration . The former registers an InfrastructureAdvisorAutoProxyCreator that scans for @Transactional annotations, while the latter defines advisors and interceptors that drive the transaction logic.

1. @EnableTransactionManagement Working Principle

Enabling transactions adds an InfrastructureAdvisorAutoProxyCreator (extending AbstractAdvisorAutoProxyCreator ) to the container. This bean acts as a BeanPostProcessor that, during bean initialization, checks whether a bean matches any BeanFactoryTransactionAttributeSourceAdvisor based on the presence of @Transactional on the class or its methods, and creates a dynamic proxy when needed.

2. Basic Execution Principle

When a proxied method is invoked, the TransactionInterceptor determines if a transaction is required. If so, it obtains a PlatformTransactionManager , creates a new database connection, sets autocommit to false, and proceeds with the business method. After execution, it either commits or rolls back the connection based on whether an exception was thrown.

Create a new database connection via the configured transaction manager.

Set autocommit to false.

Execute the target method (business logic).

If no exception, commit the transaction.

If an exception occurs, roll back the transaction.

3. Detailed Execution Flow

The InfrastructureAdvisorAutoProxyCreator checks each bean against BeanFactoryTransactionAttributeSourceAdvisor . If a match is found, the bean is wrapped with a proxy that delegates to TransactionInterceptor . The interceptor’s invoke() method orchestrates the steps listed above.

4. Transaction Propagation Mechanism

Propagation determines how nested transactional method calls behave. Common scenarios include:

Both methods share the same transaction.

Each method runs in its own transaction.

Only the outer method is transactional while the inner one is not.

Spring implements this by checking the current thread’s ThreadLocal for an existing connection. If a transaction already exists, the new method may be executed within the same transaction, or the existing transaction can be suspended and a new one started, depending on the propagation setting.

5. Propagation Types

Examples of propagation settings and their effects are demonstrated with four code scenarios:

@Component
public class UserService {
    @Autowired
    private UserService userService;

    @Transactional
    public void test() {
        // sql in test()
        userService.a();
    }

    @Transactional
    public void a() {
        // sql in a()
    }
}

Scenario 1 (REQUIRED) shows a single transaction covering both methods. Scenario 2 adds an exception in the outer method, causing a rollback of both. Scenario 3 forces an exception inside the inner method, also rolling back both. Scenario 4 uses propagation = Propagation.REQUIRES_NEW for the inner method, resulting in two separate transactions where the inner one rolls back independently, but the outer transaction still rolls back because the exception propagates.

6. Forced Rollback

Even when an exception is caught and handled, you can mark the current transaction for rollback using:

@Transactional
public void test(){
    try {
        b();
    } catch (Exception e) {
        // build friendly error response
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    }
}

public void b() throws Exception {
    throw new Exception();
}

7. TransactionSynchronization

Spring provides TransactionSynchronization callbacks to listen to transaction lifecycle events such as suspend, resume, beforeCommit, afterCommit, and afterCompletion. Example registration:

@Transactional
public void test(){
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
        @Override public void suspend(){ System.out.println("test suspended"); }
        @Override public void resume(){ System.out.println("test resumed"); }
        @Override public void beforeCommit(boolean readOnly){ System.out.println("test before commit"); }
        @Override public void beforeCompletion(){ System.out.println("test before completion"); }
        @Override public void afterCommit(){ System.out.println("test after commit"); }
        @Override public void afterCompletion(int status){ System.out.println("test after completion"); }
    });
    // business logic
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void a(){
    // similar synchronization callbacks for method a
}

These callbacks allow developers to execute custom logic when a transaction is suspended, resumed, committed, or rolled back.

BackendJavaaopSpringTransaction ManagementRollbackPropagation
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.