How does @Transactional actually work in Spring Boot?
@Transactional is declarative transaction demarcation. You mark where a transaction should start and end, and Spring supplies the begin, commit, and rollback calls. The annotation does nothing by itself. It is metadata that Spring reads when it creates the bean.
At startup, Spring sees the annotation and wraps the bean in a proxy. If the bean is proxied through an interface, the wrapper can be a JDK dynamic proxy. Otherwise it is a CGLIB-generated subclass. The container injects this proxy into every collaborator that asks for the bean, so callers never hold a reference to the real object.
When a call reaches the proxy, it passes through TransactionInterceptor. Using the configured PlatformTransactionManager, the interceptor decides whether to open a new transaction or join an existing one. It then invokes the target method and commits or rolls back depending on how that method exits. The target object is plain Java with no transactional behavior of its own. All of the transaction logic lives in the wrapper.
caller ──► proxy ──► TransactionInterceptor ──► target.methodA()
(begin / join, │
commit / rollback) │ this.methodB()
▼
target.methodB()
(direct call: no proxy, no interceptor)
This diagram is the main point of this article. Spring does not apply transactions to method calls. It applies them to calls that pass through the proxy. Inside methodA, this refers to the target, not the proxy, so this.methodB() never reaches the interceptor, regardless of how methodB is annotated.
You will debug transaction problems faster by asking one question: "Does this call cross the proxy boundary?" That works better than memorizing a list of rules about where annotations take effect.
┌─────────────┐
│ Caller bean │
└──────┬──────┘
│ service.methodA() (holds proxy reference)
▼
┌────────────────────────────────────────────────────────────┐
│ Proxy (JDK dynamic proxy or CGLIB subclass) │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ TransactionInterceptor │ │
│ │ begin / join ──► PlatformTransactionManager │ │
│ │ commit / rollback on method exit │ │
│ └──────────────────────────┬───────────────────────────┘ │
└─────────────────────────────┼──────────────────────────────┘
│ invoke target
▼
┌────────────────────────────────────────────────────────────┐
│ Target object (plain Java, no transactional behavior) │
│ │
│ methodA() { │
│ this.methodB(); ───┐ │
│ } │ direct call: `this` is the │
│ │ target, not the proxy │
│ @Transactional │ │
│ methodB() { ... } ◄───┘ TransactionInterceptor │
│ never runs: no tx begins │
└────────────────────────────────────────────────────────────┘
Calls from the caller pass through the proxy and its TransactionInterceptor. The internal this.methodB() call stays inside the target object, so methodB's @Transactional annotation is never applied.
Why does transactional self invocation in Spring silently do nothing?
Take an OrderService whose placeOrder() is annotated @Transactional. Partway through, it calls writeAuditLog(), which is annotated @Transactional(propagation = REQUIRES_NEW) so the audit row survives even if the order fails. Then inventory validation throws a RuntimeException. You expect the order to roll back and the audit row to remain. Instead, both disappear.
placeOrder() was entered through the proxy, so the transaction interceptor ran. Once inside the target object, writeAuditLog() is invoked on this, which is the raw bean, not the proxy. No interceptor sees that call, so Spring never reads its annotation. The method runs as ordinary Java inside the outer transaction, and its insert is rolled back with everything else. The same applies to readOnly, timeout, isolation, and rollbackFor on the inner method. Spring logs no warning because, from its point of view, nothing was called.
Several other failures have the same cause: the call never passes through the proxy.
| Scenario | Why the proxy is bypassed | Typical symptom |
|---|---|---|
this.method() call |
Invocation stays on the target instance | Inner propagation and readOnly ignored |
private method |
Proxy-based AOP doesn't advise it by default | Annotation has no effect |
final method |
A CGLIB subclass can't override it, so no interception | No transaction, or odd null fields |
Constructor or @PostConstruct |
Runs on the raw bean before the proxy wraps it | Writes happen outside any transaction |
Any backend engineer who splits a long service method into annotated helpers in the same class can hit this. The code compiles, the tests usually pass, and the bug appears when a rollback path runs.
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class OrderService {
private final OrderRepository orders;
private final AuditLogRepository auditLogs;
public OrderService(OrderRepository orders, AuditLogRepository auditLogs) {
this.orders = orders;
this.auditLogs = auditLogs;
}
// Entered through the proxy: the interceptor opens transaction T1.
@Transactional
public void placeOrder(Order order) {
orders.save(order);
// Called on 'this' (the raw target), not on the proxy.
// No interceptor runs, so REQUIRES_NEW is never read.
// The insert joins T1 instead of getting its own transaction.
writeAuditLog(order.getId(), "ORDER_ATTEMPTED");
// Throws RuntimeException -> T1 rolls back the order AND the audit row.
validateInventory(order);
}
// Intended to commit independently, but only works when called via the proxy.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void writeAuditLog(Long orderId, String event) {
auditLogs.save(new AuditLog(orderId, event));
}
private void validateInventory(Order order) {
if (order.getQuantity() > 100) {
throw new IllegalStateException("Insufficient stock for order " + order.getId());
}
}
}
placeOrder() calls writeAuditLog() on the target object rather than the proxy, so REQUIRES_NEW is ignored and the audit insert is rolled back with the failed outer transaction.
How do propagation and rollback rules behave once the call crosses the proxy?
Propagation settings and rollback rules are read by the transaction interceptor, so they only apply when the call passes through the proxy. On a self-invoked method, REQUIRES_NEW does nothing because the interceptor never sees the call.
| Propagation | Behaviour when crossing the proxy | Trade-off |
|---|---|---|
REQUIRED (default) |
Joins the existing transaction or starts one | Inner failures affect the outer transaction |
REQUIRES_NEW |
Suspends the outer transaction and opens its own | Needs a second connection while the first is still held |
NESTED |
Creates a savepoint inside the outer transaction | Depends on transaction manager and driver savepoint support |
REQUIRES_NEW is the usual choice for audit logs and outbox writes. Under load, though, each request holds two connections at once. If enough threads hold their outer connection while waiting for a second one, the pool can run dry and stall. NESTED avoids the second connection, but it does not work on every stack, so code that relies on it may not move between transaction managers.
By default, Spring rolls back on RuntimeException and Error but not on checked exceptions. rollbackFor and noRollbackFor change that. Setting rollbackFor = Exception.class everywhere also rolls back cases where the business logic intended to log a checked exception and continue.
The interceptor only reacts to exceptions that leave the method. If you catch an exception inside the method, the transaction commits unless you rethrow it or call setRollbackOnly().
There is also a trap when the outer method catches and continues. An inner REQUIRED method throws, and the interceptor marks the shared transaction rollback-only. The outer method catches the exception and keeps going. At commit, Spring finds the rollback-only flag and throws UnexpectedRollbackException.
@Service
class OrderService {
private final OrderRepository orders;
private final AuditService audit; // separate bean, so calls go through its proxy
OrderService(OrderRepository orders, AuditService audit) {
this.orders = orders;
this.audit = audit;
}
@Transactional
public void placeOrder(Order order) {
orders.save(order);
try {
audit.record(order); // REQUIRED: joins this same transaction
} catch (IllegalStateException e) {
// The exception is swallowed here, but the interceptor around record()
// has already marked the shared transaction rollback-only.
}
} // On commit, Spring finds the rollback-only flag and throws UnexpectedRollbackException
@Transactional
public void placeOrderWithExplicitRollback(Order order) {
orders.save(order);
try {
audit.recordIndependently(order);
} catch (IllegalStateException e) {
// The REQUIRES_NEW inner transaction already rolled back on its own.
// The outer transaction is unaffected unless we choose to roll it back:
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
}
@Service
class AuditService {
@Transactional // default REQUIRED: a failure here poisons the caller's transaction
public void record(Order order) { throw new IllegalStateException("audit store unavailable"); }
@Transactional(propagation = Propagation.REQUIRES_NEW) // suspends the outer transaction and uses a second connection
public void recordIndependently(Order order) { throw new IllegalStateException("audit store unavailable"); }
}
An inner REQUIRED call that throws marks the shared transaction rollback-only, so the outer catch-and-continue fails at commit with UnexpectedRollbackException. With REQUIRES_NEW, the inner failure stays isolated, and setRollbackOnly() lets the outer method roll back explicitly when it needs to.
How can you detect proxy boundary bugs instead of guessing?
That kind of failure only shows up when you look at what the transaction infrastructure is doing. Reasoning from the code doesn't reveal it.
Make the transaction manager narrate
Set logging.level.org.springframework.transaction to DEBUG. If you use JPA, also set the package of your concrete manager, such as org.springframework.orm.jpa. The transaction manager logs when it creates a new transaction, when a call participates in an existing one, and when it suspends one for REQUIRES_NEW. The interceptor package logs per-method transaction acquisition at a finer level, so enable TRACE on org.springframework.transaction.interceptor if you want each method name. A self-invoked method is identified by what is missing: no log line names it. That is the clearest evidence you will get that the call never crossed the proxy.
Assert inside the method, in a test
Logs need someone to read them, and a test does not. Inside the method you want to verify, or in a test hook it calls, assert TransactionSynchronizationManager.isActualTransactionActive(). The assertion fails the moment a refactor turns a proxied call into an internal one.
Test rollback against a real database
Mocked repositories cannot fail this way, because no transaction exists to roll back. Run integration tests against a real or containerized database. Trigger the failure path, then query the database in a separate transaction and assert that the rows are absent.
These tests are slower than mocked unit tests. Build time grows, and CI needs a database. The alternative is a passing mock suite that ships the bug, followed by a data-inconsistency investigation in production. That investigation usually costs more engineering hours than the extra test runtime ever will. Keep the slow tests few and target them at the transactional boundaries.
// Integration test against a real (or containerized) database, no mocked repositories.
// Deliberately NOT annotated with @Transactional: a test-managed transaction would
// wrap the service call and hide whether the service opened its own transaction.
@SpringBootTest
class OrderServiceRollbackIT {
@Autowired OrderService orderService; // placeholder service under test
@Autowired JdbcTemplate jdbc;
@AfterEach
void cleanUp() {
jdbc.update("DELETE FROM orders WHERE customer_id = ?", "cust-42");
}
@Test
void failedOrderLeavesNoRows() {
// Failure path: placeOrder inserts a row, then throws on an invalid quantity.
// If placeOrder reaches a @Transactional method via this.method(), the proxy
// is bypassed, nothing rolls back, and the row is committed.
assertThrows(IllegalArgumentException.class,
() -> orderService.placeOrder("cust-42", "SKU-1001", -1));
// This query runs outside the service's transaction, so it sees only committed data.
Integer rows = jdbc.queryForObject(
"SELECT COUNT(*) FROM orders WHERE customer_id = ?", Integer.class, "cust-42");
assertEquals(0, rows, "insert was committed: the call likely never crossed the proxy");
}
@Test
void noTransactionLeaksIntoTheTestThread() {
// Sanity check that the test itself isn't transactional, which would mask the bug.
assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
}
}
A non-transactional Spring Boot integration test triggers a failure path against a real database and then checks committed state, so a self-invoked @Transactional method that skips rollback makes the test fail.
What are the alternatives for fixing @Transactional self-invocation?
The options below are ranked from clearest to most intrusive. Each one makes the call pass through transactional advice, but each changes the code structure in a different way.
1. Move the inner method into a separate bean
Extract the method into a separate collaborator, such as LedgerWriter, and inject that collaborator into the original service. The call ledgerWriter.record(...) now goes through the collaborator's proxy, so its @Transactional(propagation = REQUIRES_NEW) is applied. This works best when the split reflects a real responsibility. If you extract a class only to get a proxy boundary, you end up with a bean whose name explains nothing.
2. Use TransactionTemplate
Inject a TransactionTemplate and wrap the code that needs a transaction in transactionTemplate.execute(status -> ...). Configure propagation and isolation on the template, for example with setPropagationBehavior(...), and call status.setRollbackOnly() to roll back without throwing. The transaction boundary is visible in the method body, so a reader does not need to know how proxies work. The cost is boilerplate, and you need separate template instances when different blocks need different settings.
3. Self-inject the proxy
Inject the service into itself with @Lazy on the field or constructor parameter, or use ObjectProvider<OrderService>, and call self.inner() or provider.getObject().inner(). The call then goes through the proxy. This is a workaround. It hides a structural problem and depends on a circular reference that a future refactor can easily break.
4. Switch to AspectJ weaving
Set @EnableTransactionManagement(mode = AdviceMode.ASPECTJ), add spring-aspects, and configure compile-time or load-time weaving. The transactional advice is then woven into the class bytecode itself. As a result, self-calls are intercepted, and so are non-public methods. The trade-off is that your build pipeline and runtime startup now depend on the weaving setup working correctly.
When should you avoid each fix, and what does it cost the team?
Each of these fixes works. They differ in what they cost the people who read, build and test the code afterwards.
| Fix | Readability | Build complexity | Testability | Team familiarity |
|---|---|---|---|---|
| Split into a separate bean | Good when the split matches a real responsibility, poor when it doesn't | None | Good: each bean is mocked or tested on its own | High |
| Self-injection | Poor: the proxy dependency is hidden | None, but may need @Lazy |
Awkward: unit tests have to wire the bean to itself | Low |
| AspectJ weaving | Good at call sites | High: compile-time or load-time setup | Tests must run with the weaver active | Low |
TransactionTemplate |
Mixed: transaction handling sits inside business code | None | Good: you control the transaction manager | Moderate |
Bean splitting is the default choice when the extracted method does its own job. It goes wrong when you split mechanically. Classes like OrderServiceInternal exist only to get around the proxy, and readers have to jump between files to follow a single operation.
Self-injection removes the bug but hides the reason. A reader who sees self.process() has no clue that the call has to go through the proxy. Recent Spring Boot versions reject circular references by default, so this pattern often fails at startup until someone adds @Lazy. Avoid it outside of short-term patches.
AspectJ makes sense if the team already runs weaving in its build. Otherwise it changes the rules your teammates expect. Proxy-mode assumptions such as "private methods are ignored" no longer apply, and a test run without the weaver behaves differently from production.
TransactionTemplate works well for a small number of explicit, fine-grained transaction boundaries. Spread across many call sites, it invites inconsistent rollback handling. Some callbacks call setRollbackOnly(), some rely on runtime exceptions, and the rollbackFor rules you configured on @Transactional methods do not apply to any of them.
How should you design service boundaries so transactions behave predictably?
Most self-invocation bugs come from treating @Transactional as a property of individual methods rather than of the boundary between components. A more reliable rule: put the transaction on the public method of a service that controllers, message listeners, or schedulers call, and nowhere below it. External callers always go through the proxy, so the annotation takes effect wherever it appears. Inner helpers then run inside the transaction their caller already opened, and they don't need their own annotations.
Problems start when one class mixes annotated and unannotated methods that call each other, because correctness then depends on proxy mechanics that are invisible during review. If a step truly needs different semantics, such as an audit write that must commit even when the main work rolls back, move it into a separate bean whose name states that intent. Readers should be able to see the boundary in the class structure, not work it out from annotation attributes.
Keep transactions short. A transaction that wraps an HTTP call or a slow queue publish holds a pooled connection and any row locks for the full network round trip. Under load, that drains the pool and causes lock waits in requests that have nothing to do with the remote call. Fetch remote data before the transaction starts, and publish after it commits.
Use declarative @Transactional for the standard case of one unit of work per entry point. Use TransactionTemplate when a single method needs several independent commits, as in batch processing with per-chunk boundaries, and keep that code out of ordinary services.
Consistent conventions also make reviews and incidents faster. A reviewer only has to confirm that the annotation is on the entry point. During an incident, the team already knows where each transaction starts and ends.
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 transactional self invocation spring, 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.
- The dependency graph answers "what does this touch?" in seconds instead of a manual audit.
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.
- You can size a change's blast radius before merging, avoiding surprise cross-team firefighting.
- 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.