How does it work? Inside @Transactional in Spring

@Transactional is metadata, not behavior. The annotation itself does nothing at runtime. When Spring creates a bean whose class or methods carry it, Spring wraps that bean in an AOP proxy and registers the proxy in the application context instead of the raw object. Any other bean that injects your service receives the proxy.

Spring builds that proxy in one of two ways:

  • JDK dynamic proxy: Spring generates a class that implements the bean's interfaces. Callers can only see interface methods, so methods that are not on the interface get no transactional behavior.
  • CGLIB subclass proxy: Spring generates a runtime subclass that overrides the bean's methods. This works without interfaces, but it cannot intercept final or private methods because those cannot be overridden. Spring Boot configures class-based proxying by default.

Either way, a call on the proxy goes to a transaction interceptor. The interceptor reads the method's transaction attributes, such as propagation, isolation, read-only and rollback rules. It then asks the configured transaction manager to start a new transaction or join an existing one. Next it invokes the real method on the target object. When the method returns, the interceptor commits. If the method throws an exception that matches the rollback rules, the interceptor rolls back.

Teams use declarative transactions because they keep connection handling, commit and rollback logic out of business code. The cost is a rule this article builds on: the interceptor runs only when a call passes through the proxy. A call that reaches the target object directly skips the interceptor, and the annotation has no effect.

 +-------------------------+
 | Caller bean             |
 | (injected ref = proxy)  |
 +------------+------------+
              | service.placeOrder()
              v
 +-----------------------------------------------+    +-------------------+
 | AOP proxy (registered in application context) |    | Transaction       |
 |  JDK: implements interfaces only              |    | manager           |
 |  CGLIB: subclass; no final/private methods    |    +---------+---------+
 |                                               |              ^
 |  Transaction interceptor                      |              |
 |   1. read attributes: propagation, isolation, |              |
 |      read-only, rollback rules                |              |
 |   2. begin new or join existing tx -----------+--------------+
 |   3. invoke target --------+                  |              |
 |   4. commit or roll back on match ------------+--------------+
 +----------------------------|------------------+
                              v
              +-------------------------------+
              | Target object (raw bean)      |
              | placeOrder() business logic   |
              | this.other() skips the proxy, |
              |   interceptor does not run    |
              +-------------------------------+

Callers hold the proxy, so the transaction interceptor reads the attributes, begins or joins a transaction through the transaction manager, invokes the target, then commits or rolls back; a call made from inside the target never passes through the proxy, so the interceptor does not run.

Why does Spring transactional self invocation ignore the annotation?

Self-invocation means one method on a bean calls another method on the same bean through this. That call never passes through the proxy, so the transaction interceptor never gets a chance to read the annotation.

Consider an OrderService whose placeOrder() is annotated @Transactional and calls this.recordAudit(), which is annotated @Transactional(propagation = Propagation.REQUIRES_NEW). The intent is for the audit row to commit independently, even if the order fails. In practice, recordAudit() runs inside the outer transaction, and a rollback in placeOrder() discards the audit row as well. A readOnly = true hint on the inner method is ignored for the same reason.

The caller already holds the proxy, and the proxy has already delegated to the target. From that point on, this refers to the target object, not the proxy. The inner call is an ordinary Java method dispatch, so no advice runs. Spring does not log a warning, because nothing about the call looks unusual at runtime.

The same mechanism causes other silent no-ops:

  • Private methods cannot be overridden by a subclass proxy, and Spring will not apply transactional advice to them.
  • Final methods under CGLIB cannot be overridden. The call runs directly on the proxy instance with no interception. Fields that were injected into the target may be null on that instance.
  • Objects created with new were never registered with the container, so no proxy was ever created for them.
Call pattern Through proxy? Annotation applied?
Injected bean calls other.method() on another bean Yes Yes
this.method() inside the same bean No No
Call to a private method No No
Call to a final method on a CGLIB proxy No No
Call on an instance created with new No No
@Service
public class OrderService {

    private final OrderRepository orders;
    private final AuditService auditService; // separate bean, injected as a proxy

    public OrderService(OrderRepository orders, AuditService auditService) {
        this.orders = orders;
        this.auditService = auditService;
    }

    @Transactional
    public void placeOrder(Order order) {
        // BROKEN: plain call on the target object, so REQUIRES_NEW is ignored
        // and the audit row rolls back together with the order.
        this.recordAudit(order.getId());

        // WORKS: the call goes through AuditService's proxy, which suspends
        // the outer transaction and starts a new one.
        auditService.recordAudit(order.getId());

        orders.save(order); // if this throws, only the proxied audit row survives
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void recordAudit(Long orderId) { /* never intercepted when called via this */ }
}

@Service
class AuditService {
    private final AuditRepository audits;

    AuditService(AuditRepository audits) { this.audits = audits; }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void recordAudit(Long orderId) {
        audits.save(new AuditEntry(orderId, "ORDER_PLACED")); // commits on its own
    }
}

The self-invoked recordAudit() joins the outer transaction because the call never reaches the proxy, while the same method on a separately injected AuditService bean is intercepted and runs in its own REQUIRES_NEW transaction.

What are the alternatives for fixing self-invocation?

The fixes below are ranked from clearest to least clear. Each one tries to make the call cross a proxy boundary, or to remove the need for a proxy.

  1. Extract the inner method into a separate bean. Move processItem into an ItemProcessor service and inject it. The call then goes through that bean's proxy, so the annotation applies. The transaction boundary is also visible in the class structure. The cost is fragmentation: in a large codebase this can produce many thin classes that exist only to hold one transactional method.
  2. Use TransactionTemplate. Wrap the work in transactionTemplate.execute(status -> ...). The boundary is explicit and does not depend on proxies, so self-invocation stops mattering. The downside is verbosity. Propagation and isolation are set on the template instead of being declared, and that code is repeated wherever you need a non-default configuration.
  3. Inject a lazy self-reference or ObjectProvider. Use @Lazy on a field of the bean's own type, or ObjectProvider<OrderService>, and call through it. This works, but the code now depends on proxy mechanics. A reader has to know why self.process() differs from this.process().
  4. Switch to AspectJ weaving. Set mode = AdviceMode.ASPECTJ. The advice is woven into the bytecode, so internal calls and non-public methods are covered. The cost is a compile-time or load-time weaving setup that every build and IDE must reproduce.
  5. Use AopContext.currentProxy(). This requires exposeProxy = true and ties business code directly to the Spring AOP API. Keep it as a last resort.
Fix Clarity Main cost Maintenance impact
Separate bean High More classes Low; standard DI
TransactionTemplate High Verbose code Low–medium; boundaries explicit
Lazy self / ObjectProvider Medium Proxy coupling Medium; non-obvious idiom
AspectJ weaving Medium Build complexity High; tooling setup
AopContext.currentProxy() Low Framework coupling High; fragile config flag
// Fix 1: extract the transactional method into its own bean.
@Service
class ItemProcessor {
    // Called from OrderService through this bean's proxy, so the annotation applies.
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void processItem(Item item) { /* persist item */ }
}

@Service
class OrderService {
    private final ItemProcessor itemProcessor;
    private final TransactionTemplate requiresNewTx;

    OrderService(ItemProcessor itemProcessor, PlatformTransactionManager txManager) {
        this.itemProcessor = itemProcessor;
        // Fix 2: configure a template once; propagation lives here, not in an annotation.
        this.requiresNewTx = new TransactionTemplate(txManager);
        this.requiresNewTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    }

    public void processOrder(List<Item> items) {
        for (Item item : items) {
            itemProcessor.processItem(item); // crosses a proxy boundary
        }
    }

    public void processOrderProgrammatic(List<Item> items) {
        for (Item item : items) {
            // Explicit boundary: works for a private helper, no proxy involved.
            requiresNewTx.executeWithoutResult(status -> saveItem(item));
        }
    }

    private void saveItem(Item item) { /* persist item */ }
}

Two ways to give each item its own REQUIRES_NEW transaction without self-invocation: calling a separate ItemProcessor bean through its proxy, or wrapping a private helper in a preconfigured TransactionTemplate.

Which transaction propagation modes matter in practice?

Most code needs only three of the seven modes; the other four exist to assert or exclude a transaction.

Mode Existing transaction No transaction Typical use
REQUIRED Join Create Default for service methods
REQUIRES_NEW Suspend, start independent Create Audit or outbox writes that must commit regardless
NESTED Savepoint inside outer Create Partial rollback of one step
SUPPORTS Join Run without Reads that tolerate either
MANDATORY Join Throw Assert a caller opened one
NOT_SUPPORTED Suspend Run without Slow non-transactional work
NEVER Throw Run without Assert no transaction is open

REQUIRED keeps one connection and one commit point. If any participant marks it rollback-only, the whole unit rolls back.

REQUIRES_NEW suspends the outer transaction but keeps its connection open, then borrows a second connection. That has two consequences. First, if the inner transaction touches a row the outer one has already locked, it waits on a lock held by its own thread. The outer transaction cannot release that lock until the inner one returns, so the thread blocks until a lock timeout fires. Second, it doubles connection demand per request.

Illustrative estimate. Assume a pool of 20 connections and 20 concurrent requests, each in a REQUIRED transaction that calls a REQUIRES_NEW method. All 20 connections are held by outer transactions, and all 20 inner calls wait for a free connection. Nothing progresses until the pool's acquisition timeout. With these assumed inputs, safe concurrency for this pattern is roughly pool size ÷ 2.

NESTED uses a JDBC savepoint on the same connection. It works only if the transaction manager and the database support savepoints. JTA setups commonly do not. A nested savepoint also commits or rolls back with the outer transaction, so NESTED is not a portable substitute for REQUIRES_NEW.

Why do you get UnexpectedRollbackException, and how do rollback rules work?

The rollback-only trap looks like this: an outer @Transactional method calls a method on another bean that also uses REQUIRED, so both share one physical transaction. The inner method throws a RuntimeException. When it crosses the inner proxy, the transaction interceptor applies its rollback rules. Because the inner method does not own the transaction, it cannot roll back, so it marks the shared transaction rollback-only. The outer method catches the exception and returns normally. At commit, the transaction manager finds the rollback-only flag, rolls back anyway, and throws UnexpectedRollbackException. Catching the exception did not undo the decision. The inner proxy had already made it.

By default, unchecked exceptions and Errors trigger rollback, and checked exceptions do not. The checked-exception rule assumes these represent anticipated outcomes the caller can handle. rollbackFor adds exception types that trigger rollback, and noRollbackFor exempts them. Both match subclasses as well as the named type.

Wrapping changes behavior without anyone noticing. If you convert a checked exception to a runtime one, it now rolls back. If you swallow an exception inside a transactional method, data may be committed in a partially written state.

Setting rollbackFor = Exception.class everywhere means a checked InsufficientFundsException now rolls back an audit row or status update that the caller meant to keep. Safer alternatives:

  • Return a result type for expected business outcomes instead of throwing.
  • Handle the exception inside the inner method, before it reaches the proxy.
  • Use narrow noRollbackFor entries.
  • Move work that must persist on its own into REQUIRES_NEW.
@Service
class PaymentService {
    // REQUIRED (the default) joins the caller's transaction
    @Transactional
    public void charge(long orderId) {
        // Crossing this proxy marks the SHARED transaction rollback-only
        throw new IllegalStateException("card declined");
    }

    // Safer: an expected business outcome is returned, not thrown,
    // so the interceptor sees a normal return and sets no flag
    @Transactional
    public ChargeResult tryCharge(long orderId) {
        boolean declined = true; // placeholder for a real gateway call
        return declined ? ChargeResult.DECLINED : ChargeResult.OK;
    }
}

enum ChargeResult { OK, DECLINED }

@Service
class OrderService {
    private final PaymentService payments;
    private final OrderRepository orders; // placeholder repository

    OrderService(PaymentService payments, OrderRepository orders) {
        this.payments = payments;
        this.orders = orders;
    }

    @Transactional
    public void placeOrderBroken(long orderId) {
        orders.markPending(orderId);
        try {
            payments.charge(orderId);
        } catch (IllegalStateException e) {
            orders.markDeclined(orderId); // looks handled, but...
        }
        // ...commit finds rollback-only: everything is rolled back and
        // the caller gets UnexpectedRollbackException
    }

    @Transactional
    public void placeOrder(long orderId) {
        orders.markPending(orderId);
        if (payments.tryCharge(orderId) == ChargeResult.DECLINED) {
            orders.markDeclined(orderId); // commits with the outer transaction
        }
    }
}

When an inner REQUIRED method throws a runtime exception, the shared transaction is marked rollback-only even if the outer method catches the exception, so commit fails; returning a result type for the expected outcome keeps the outer transaction committable.

How can you verify transactional behavior instead of assuming it?

Most boundary bugs hide because the code compiles, the unit tests pass, and nobody checks whether a transaction actually exists at runtime. Checking it directly takes little effort, and finding these bugs in review or CI is much cheaper than diagnosing them from production data.

Assert transaction state directly

Inside the method under test, or in a test-only collaborator it calls, assert on TransactionSynchronizationManager.isActualTransactionActive(). You can also check getCurrentTransactionName() and isCurrentTransactionReadOnly(). These checks fail when self-invocation has bypassed the proxy. Before that, the bypass only shows up as missing rollbacks.

Read the transaction manager's log

Set org.springframework.transaction to DEBUG. With JPA, also set org.springframework.orm.jpa to DEBUG. The log then shows every decision: a new transaction being created, a call participating in an existing one, suspension for REQUIRES_NEW, commit, rollback, and rollback-only marking. If you expect a new transaction and the log says "participating," you have found a propagation bug.

Test against a real database

Mocks can't flush, enforce constraints, or take locks. An in-memory substitute handles constraints, sequences, and isolation differently from your production engine. Run integration tests against the same database engine you use in production, ideally in a disposable container.

Don't let test rollback hide commit failures

A @Transactional test method rolls back by default, so the commit never happens. Deferred constraint violations only surface on flush, and UnexpectedRollbackException is thrown at commit. Neither one appears in a test that never commits. To exercise real commits:

  • Leave the test method non-transactional and call the service through its proxy. Clean up afterward by truncating tables.
  • Inside a transactional test, use TestTransaction.flagForCommit() and TestTransaction.end() to force the commit.
  • At minimum, call flush() explicitly so constraint violations fire inside the test.

When should it be used?

Use declarative @Transactional when all of the following hold:

  • The method is a public entry point on a Spring-managed bean that other beans call. That is the only case where the call reliably crosses the proxy, so the annotation does what it says.
  • The method represents one business operation whose writes must succeed or fail together. Examples are creating an order with its line items, or moving a balance between two accounts. One commit point matches one unit of business meaning.
  • The default rules fit. REQUIRED propagation, rollback on unchecked exceptions, and no rollback on checked exceptions cover most service methods without extra attributes.
  • The method needs one commit, not several. A single boundary per method is what the annotation expresses cleanly.

It is also a good fit for asserting structure. MANDATORY on a lower-level service method documents and enforces that callers must already have a transaction open. readOnly = true on query methods documents intent, with the caveats covered later in this article.

When should it be avoided?

Avoid @Transactional, or use it only with a deliberate workaround, in these cases:

  • The boundary depends on an internal call. If the transactional behavior only matters when one method of a bean calls another method of the same bean, the annotation on the inner method will be ignored. Extract a bean or use TransactionTemplate instead.
  • Private, final, or non-proxied code. Annotating a private method, a final method under CGLIB, or a class instantiated with new produces no transaction and no warning.
  • One method needs several independent commits. Processing a large batch in chunks, or committing each item separately so one failure does not undo the others, is clearer with a TransactionTemplate inside a loop than with a single annotated method.
  • The method does slow or external I/O. HTTP calls, message publishing, and file transfers inside the boundary hold a connection and possibly row locks for as long as the remote side takes.
  • Controllers and repositories. A boundary on a controller mixes web concerns with persistence. A boundary only at the repository level commits each call separately and can leave partial state.
  • Work handed to another thread. In imperative Spring code the transaction is bound to the current thread. Work submitted to an executor or an @Async method does not join the caller's transaction, even though the code may read as if it does.
  • Blanket use on every class. Annotating a whole class as a habit hides which methods actually need atomicity and makes propagation decisions implicit rather than reviewed.

How should you design transaction boundaries in a Spring Boot service?

Put the boundary on the service method that represents one business operation, such as "place order" or "approve refund". Controllers are too coarse because they mix HTTP concerns with persistence. Repositories are too fine because each call commits on its own and leaves partial state behind. One entry point per use case gives a single place to ask "what must succeed or fail together?"

Keep that unit short. A transaction holds a pooled connection and often row locks for its whole duration. HTTP calls, message publishing, file uploads and retries with backoff should run before the transaction starts or after it commits. Otherwise a slow downstream dependency becomes lock contention and pool exhaustion in your database. If an external effect must follow a commit, use an after-commit hook or an outbox table instead of calling out mid-transaction.

Treat readOnly = true as a hint, not a guarantee. Depending on the transaction manager, ORM and JDBC driver, it may skip dirty checking, set the connection read-only, or do nothing measurable. Use it to document intent, not to enforce safety.

Declarative @Transactional is the right default for straightforward use cases. Switch to TransactionTemplate when one method needs several independent commits, conditional rollback, or a boundary that would otherwise require self-invocation. Often the cleaner fix is to split the work into a separate bean.

The team that owns the service should own these decisions. A review checklist keeps them explicit:

  • Is this method a real entry point?
  • Does any I/O happen inside the boundary?
  • Which propagation applies, and why?
  • Which exceptions trigger rollback?
  • Is there a test that observes the commit?

How can it save engineering time?

Used correctly, declarative transactions remove a category of hand-written code and a category of hard-to-trace bugs.

  • Less boilerplate to write and review. Without the annotation, every service method that writes data needs code to obtain a connection, disable auto-commit, commit on success, roll back on failure, and release the connection in a finally block. The interceptor does this once, consistently, so reviewers read business logic instead of resource handling.
  • Consistent rollback behavior. Rollback rules are declared in one place per method rather than reimplemented in each catch block. That removes a common source of divergence between methods that were written by different people at different times.
  • Cheaper diagnosis. Knowing the proxy rule turns a vague symptom such as "the audit row disappeared" or "the read-only hint had no effect" into a short list of causes: self-invocation, a private or final method, or an object created with new. DEBUG logging on org.springframework.transaction then confirms the cause from the log rather than from guesswork.
  • Bugs caught before production. Tests that assert TransactionSynchronizationManager.isActualTransactionActive() and tests that force a real commit surface propagation and rollback-only mistakes in CI. Fixing them there avoids reconstructing what happened from partially committed production data.
  • Faster reviews with a shared vocabulary. The checklist in the previous section, plus the ranked fixes for self-invocation, gives a team agreed answers to recurring questions. Reviews spend less time re-arguing where a boundary belongs or which workaround to use.

The time savings depend on respecting the proxy rule. An annotation that silently does nothing costs more time than explicit code, because the failure shows up later and far from its cause. Verifying boundaries with logs and commit-observing tests is what makes the declarative approach a net saving.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to spring transactional self invocation, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.