Sub topic 16
Case study: @Transactional as proxy advice
This chapter assumes you know Spring beans and dependency injection, and that you have read the earlier chapters on JDK and CGLIB proxies, around advice, and self-invocation. Here you will see that @Transactional is not special syntax. It is around advice applied by a proxy, and the rules you learned for proxies explain every well-known transaction gotcha.
What the proxy does
When Spring finds a bean with @Transactional on its class or methods, it wraps the bean in a proxy. The proxy carries a transaction interceptor (TransactionInterceptor), which is an around advice. On each call that passes through the proxy, the interceptor does roughly this:
- Look up the
@Transactionalattributes for the called method. - Ask the
PlatformTransactionManagerto start or join a transaction, based on the propagation setting. - Call the real method with
proceed(). - If the method returns normally, commit. If it throws, decide whether to roll back, then rethrow.
You could write a simplified version yourself. The sketch below shows the shape, not the real implementation.
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
@Aspect
@Component
public class SimpleTxAspect {
private final PlatformTransactionManager txManager;
public SimpleTxAspect(PlatformTransactionManager txManager) {
this.txManager = txManager;
}
@Around("@annotation(org.springframework.transaction.annotation.Transactional)")
public Object inTransaction(ProceedingJoinPoint pjp) throws Throwable {
TransactionStatus status = txManager.getTransaction(new DefaultTransactionDefinition());
try {
Object result = pjp.proceed();
txManager.commit(status);
return result;
} catch (Throwable t) {
txManager.rollback(status);
throw t;
}
}
}Do not run this next to the real @Transactional support. Both would open transactions around the same call.
How the proxy is chosen
The rules from the proxy-creation chapter apply unchanged. A bean that implements an interface gets a JDK proxy by default in plain Spring. Spring Boot sets spring.aop.proxy-target-class=true by default, so Boot applications use CGLIB even when interfaces exist. In both cases, injection by type works only for what the proxy exposes. With a JDK proxy, you must inject the interface, not the concrete class. Injecting the class fails with a type mismatch.
Rollback rules
The interceptor does not roll back on every exception. By default it rolls back on unchecked exceptions (RuntimeException and Error) and commits on checked exceptions. This surprises many developers.
import java.io.IOException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class ImportService {
// Commits even though an exception escapes: IOException is checked.
@Transactional
public void importDefault() throws IOException {
throw new IOException("disk error");
}
// Rolls back for checked exceptions too.
@Transactional(rollbackFor = Exception.class)
public void importStrict() throws IOException {
throw new IOException("disk error");
}
}A related trap is swallowing the exception inside the method. If you catch it and return normally, the interceptor sees a normal return and commits. The proxy can only react to what crosses its boundary.
Self-invocation and propagation
The self-invocation rule hits transactions hard. Recall the ReportService example from the self-invocation chapter. saveAll calls saveReport on this, so the REQUIRES_NEW setting is ignored. Whatever transaction state saveAll has is what saveReport uses.
The same applies in the other direction. An unannotated public method that calls a @Transactional method on this runs with no transaction at all.
You have three common fixes:
- Move the inner method to another bean and inject that bean. This is the cleanest option.
- Inject a reference to the proxy into the bean (for example through
ObjectProvideror a lazy self-reference) and call through it. - Use AspectJ weaving with
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ), which changes the bytecode so that even internal calls are advised.
Prefer the first. The others make the class depend on its own proxying.
Visibility, final and thread limits
The proxy limitations chapter applies here as well.
| Situation | Effect on `@Transactional` |
|---|---|
| `private` method | Never intercepted. The annotation has no effect. |
| `final` method or class, with CGLIB | The method cannot be overridden, so it runs without a transaction. |
| Object created with `new` | Not a Spring bean, so no proxy and no transaction. |
| Package-private or protected method | Supported by class-based proxies in current Spring versions, but public methods remain the safe choice. |
| Call from another thread | The transaction is bound to the thread that started it. A new thread has none. |
The last row is not about proxies. The transaction manager keeps the current transaction in thread-bound state. If a transactional method hands work to an executor, that work does not take part in the transaction.
Timing: commit happens after your method
Because the commit occurs in the proxy after proceed() returns, the caller sees the result of a method before the data is committed only in the sense that code inside the method has finished. Failures at commit time, such as a constraint violation flushed by the database, are thrown from the proxy. A try/catch inside the transactional method cannot catch them. Handle those in the caller, or in an outer layer.
Also remember advice ordering. The transaction advice has a configurable order (@EnableTransactionManagement(order = ...)). If you write your own aspect, for example a retry aspect, its position relative to the transaction advice decides whether each retry gets a fresh transaction. A retry aspect must run outside the transaction advice. Otherwise it retries inside one transaction that may already be marked rollback-only.
Checking that the proxy is there
When a transaction seems missing, confirm the proxy before guessing. Two quick checks help:
- Call
AopUtils.isAopProxy(bean)on the injected bean. - Inside the method, call
TransactionSynchronizationManager.isActualTransactionActive().
import org.springframework.aop.support.AopUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;
@Component
public class TxProbe {
public void inspect(Object bean) {
System.out.println("proxy: " + AopUtils.isAopProxy(bean));
}
public void insideMethod() {
System.out.println("active tx: " + TransactionSynchronizationManager.isActualTransactionActive());
}
}Enabling logging.level.org.springframework.transaction.interceptor=TRACE also logs each transaction that the interceptor starts and completes.
Exercise
A @Service class has a public method process() with no annotation. It calls another public method persist() in the same class, which is annotated @Transactional(rollbackFor = Exception.class). persist() throws an exception, and the data it wrote stays in the database. Give two reasons the rollback may not have happened, and one fix.
Show answer
First, process() calls persist() on this, so the call skips the proxy and the transaction interceptor never runs. Without a transaction, there is nothing to roll back, and the writes were committed or auto-committed on their own. Second, if persist() or a caller catches the exception and returns normally, the interceptor sees a normal return and commits. The fix for the first cause is to move persist() to a separate bean and inject it, so the call goes through that bean's proxy.