Proxies behind @Transactional
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite saves an order and reduces stock in two steps; if the second step fails, the first must be undone. @Transactional does that through a proxy, and that one fact explains its famous bugs.
What Spring wraps around a @Transactional bean
A proxy is an object of the same type as the real object. It receives each call first, adds work before or after, and then forwards the call. Spring puts one in front of a @Transactional bean.
Spring does not inject the OrderService bean itself. It injects a proxy, created for you at startup, and your controller talks to that.
@Servicepublic class OrderService { private final OrderRepository orders; private final StockRepository stock; public OrderService(OrderRepository orders, StockRepository stock) { this.orders = orders; this.stock = stock; }
@Transactional // the proxy runs this method inside one transaction public void placeOrder(Order order) { orders.save(order); stock.reduce(order.productId(), order.quantity()); }}Example 1 · Seeing the proxy Spring injects
Runs in: a Spring Boot project
package com.shoplite.order;
import org.springframework.aop.support.AopUtils;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class ProxyCheck implements CommandLineRunner { private final OrderService orderService; // has @Transactional methods
public ProxyCheck(OrderService orderService) { this.orderService = orderService; }
@Override public void run(String... args) { System.out.println("Injected class: " + orderService.getClass().getName()); System.out.println("Is a proxy: " + AopUtils.isAopProxy(orderService)); System.out.println("Real class: " + AopUtils.getTargetClass(orderService).getSimpleName()); }}Injected class: com.shoplite.order.OrderService$$SpringCGLIB$$0 Is a proxy: true Real class: OrderService
What this code does
- The injected object's class is a generated subclass of
OrderService, which is why every caller goes through the transaction logic. AopUtils.getTargetClassshows the real class behind the proxy. Your own code never needs to name the proxy class.
The call path is: controller → proxy → transaction logic → real placeOrder → back through the proxy. Spring Boot creates class-based proxies by default (a generated subclass, made with the CGLIB library), so the proxy's class name contains SpringCGLIB, as Example 1 shows.
Order of execution
The path of one call
Tap the steps in the order they happen.
Begin, commit and rollback inside the proxy
rollbackFor lists checked exception types that should also roll back the transaction. By default only RuntimeException and Error do.
Inside the proxy, Spring begins a transaction, calls your method, and then decides the ending from how the method finished.
Example 2 · A hand-written transactional proxy
import java.io.IOException;
interface OrderService { void placeOrder(String orderId, int qty) throws IOException;}
class RealOrderService implements OrderService { public void placeOrder(String orderId, int qty) throws IOException { System.out.println(" save " + orderId + ", reduce stock by " + qty); if (qty > 5) { throw new IllegalStateException("only 5 in stock"); } if (orderId.endsWith("X")) { throw new IOException("invoice printer offline"); } }}
// What Spring's proxy does for a @Transactional method, written by handclass TransactionalOrderService implements OrderService { private final OrderService target;
TransactionalOrderService(OrderService target) { this.target = target; }
public void placeOrder(String orderId, int qty) throws IOException { System.out.println(" BEGIN"); try { target.placeOrder(orderId, qty); System.out.println(" COMMIT"); } catch (RuntimeException | Error e) { System.out.println(" ROLLBACK (" + e.getMessage() + ")"); throw e; } catch (IOException e) { System.out.println(" COMMIT, checked exception (" + e.getMessage() + ")"); throw e; } }}
public class HandProxyDemo { public static void main(String[] args) { OrderService orders = new TransactionalOrderService(new RealOrderService()); String[][] calls = {{"ORD-1", "2"}, {"ORD-2", "9"}, {"ORD-3X", "1"}}; for (String[] c : calls) { System.out.println(c[0] + ":"); try { orders.placeOrder(c[0], Integer.parseInt(c[1])); } catch (Exception e) { System.out.println(" caller got " + e.getClass().getSimpleName()); } } }}ORD-1:
BEGIN
save ORD-1, reduce stock by 2
COMMIT
ORD-2:
BEGIN
save ORD-2, reduce stock by 9
ROLLBACK (only 5 in stock)
caller got IllegalStateException
ORD-3X:
BEGIN
save ORD-3X, reduce stock by 1
COMMIT, checked exception (invoice printer offline)
caller got IOExceptionWhat this code does
TransactionalOrderServicehas the same interface as the real service and wraps each call in BEGIN and COMMIT or ROLLBACK, as Spring's proxy does.- ORD-2 throws an unchecked exception and rolls back. ORD-3X throws a checked
IOExceptionand still commits, which is Spring's default rule.
The surprising rule: by default a checked exception commits, because Spring treats it as an expected business outcome. Use @Transactional(rollbackFor = SomeCheckedException.class) when it must undo the work.
How the method finished decides the ending:
- Normal return → commit.
RuntimeExceptionorError→ rollback, then rethrow.- Checked exception → commit, then rethrow (unless listed in
rollbackFor).
Predict the output
Commit or rollback?
Pick what happens to the saved order.
Round 1 of 3
What happens to the saved order?
Self-invocation and private methods
Self-invocation is a bean calling one of its own methods through this. The call goes to the real object, not through the proxy, so @Transactional on the called method is ignored.
A batch method loops over orders and calls placeOrder for each. Written as placeOrder(o), the call is really this.placeOrder(o).
// Fix: move the batch loop to another bean, so each call goes through the proxy@Servicepublic class BatchOrderService { private final OrderService orders; // this is the proxy
public BatchOrderService(OrderService orders) { this.orders = orders; }
public void placeAll(List<Order> batch) { for (Order o : batch) { orders.placeOrder(o); // @Transactional now applies to each order } }}Example 3 · Self-invocation skips the proxy
import java.util.List;
interface OrderService { void placeOrder(String orderId); void placeAll(List<String> orderIds);}
class RealOrderService implements OrderService { public void placeOrder(String orderId) { System.out.println(" save " + orderId); }
public void placeAll(List<String> orderIds) { for (String id : orderIds) { this.placeOrder(id); // a call on "this", not on the proxy } }}
class TransactionalProxy implements OrderService { private final OrderService target;
TransactionalProxy(OrderService target) { this.target = target; }
public void placeOrder(String orderId) { System.out.println(" BEGIN"); target.placeOrder(orderId); System.out.println(" COMMIT"); }
public void placeAll(List<String> orderIds) { target.placeAll(orderIds); // not transactional: passed straight through }}
public class SelfInvocationDemo { public static void main(String[] args) { OrderService orders = new TransactionalProxy(new RealOrderService());
System.out.println("Direct call through the proxy:"); orders.placeOrder("ORD-7");
System.out.println("placeAll calling this.placeOrder:"); orders.placeAll(List.of("ORD-8", "ORD-9")); }}Direct call through the proxy:
BEGIN
save ORD-7
COMMIT
placeAll calling this.placeOrder:
save ORD-8
save ORD-9What this code does
- Calling
placeOrderthrough the proxy prints BEGIN and COMMIT. InsideplaceAll,this.placeOrderis a call on the real object, so no transaction starts. - Nothing fails or warns: the orders are saved without a transaction, which is exactly why this bug is easy to miss.
The proxy only sees calls that come from outside the bean. Private methods are never intercepted either, because a generated subclass cannot override them. From Spring 6.0, class-based proxies also handle protected and package-private methods, but public methods are the safe choice. In all these cases Spring gives no error: the code just runs without a transaction.
Find the bug
Find the missing transaction
Click the line that skips the proxy.
Orders are saved without a transaction. Which line is the cause?
Round 1 of 3TransactionTemplate for a programmatic transaction, but moving the method to a separate bean is the clearest.Simulating a transactional proxy with java.lang.reflect.Proxy
A JDK dynamic proxy is an object created at runtime by java.lang.reflect.Proxy. It implements given interfaces and sends every call to one InvocationHandler.
The Structural Patterns module used Proxy for a timing proxy. The same tool can read a method's annotation and wrap only the marked methods in begin and commit.
Example 4 · A generated proxy that reads @Tx
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface Tx { }
interface InventoryService { @Tx void reserve(String product, int qty);
int stockOf(String product);}
class RealInventoryService implements InventoryService { public void reserve(String product, int qty) { if (qty <= 0) { throw new IllegalArgumentException("qty must be positive"); } System.out.println(" reserve " + qty + " x " + product); }
public int stockOf(String product) { return 12; }}
class Transactions { @SuppressWarnings("unchecked") static <T> T wrap(T target, Class<T> type) { InvocationHandler handler = (proxy, method, args) -> { if (!method.isAnnotationPresent(Tx.class)) { return method.invoke(target, args); // no @Tx: pass straight through } System.out.println(" BEGIN " + method.getName()); try { Object result = method.invoke(target, args); System.out.println(" COMMIT " + method.getName()); return result; } catch (InvocationTargetException e) { System.out.println(" ROLLBACK " + method.getName()); throw e.getCause(); // rethrow the real exception } }; return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler); }}
public class DynamicTxProxyDemo { public static void main(String[] args) { InventoryService inventory = Transactions.wrap(new RealInventoryService(), InventoryService.class);
inventory.reserve("Earbuds", 2); System.out.println("Stock: " + inventory.stockOf("Earbuds")); try { inventory.reserve("Hoodie", 0); } catch (IllegalArgumentException e) { System.out.println("Caller got: " + e.getMessage()); } System.out.println("Proxy class is generated: " + Proxy.isProxyClass(inventory.getClass())); }} BEGIN reserve
reserve 2 x Earbuds
COMMIT reserve
Stock: 12
BEGIN reserve
ROLLBACK reserve
Caller got: qty must be positive
Proxy class is generated: trueWhat this code does
Proxy.newProxyInstancebuilds the proxy at runtime; the handler wraps only methods marked@Tx.stockOfpasses straight through.- The real exception arrives inside
InvocationTargetException;getCause()rethrows the originalIllegalArgumentExceptionto the caller.
The handler checks for a runtime annotation such as @Tx; methods without it pass straight through. Exceptions from the real method arrive wrapped in InvocationTargetException, so the handler unwraps them with getCause() before rethrowing. This is close to how Spring's interface-based proxies work; Spring Boot's default is the CGLIB kind, a generated subclass.
The same mechanism behind @Cacheable and @Async
@Cacheable and @Async use the same kind of proxy with different logic around the call.
@Cacheable("products") // proxy: look in the cache firstpublic ProductResponse findById(int id) { ... }
@Async // proxy: run on another threadpublic CompletableFuture<Void> sendConfirmation(Order order) { ... }Example 5 · The same mechanism as a caching proxy
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;
@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface Cached { }
interface ProductCatalog { @Cached String findName(int productId);}
class DatabaseProductCatalog implements ProductCatalog { public String findName(int productId) { System.out.println(" (database query for " + productId + ")"); return productId == 7 ? "Earbuds" : "Notebook"; }}
class Caching { @SuppressWarnings("unchecked") static <T> T wrap(T target, Class<T> type) { Map<List<Object>, Object> cache = new HashMap<>(); return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, (proxy, method, args) -> { if (!method.isAnnotationPresent(Cached.class)) { return method.invoke(target, args); } List<Object> key = List.of(method.getName(), Arrays.asList(args)); if (cache.containsKey(key)) { return cache.get(key); } try { Object result = method.invoke(target, args); cache.put(key, result); return result; } catch (InvocationTargetException e) { throw e.getCause(); } }); }}
public class CachingProxyDemo { public static void main(String[] args) { ProductCatalog catalog = Caching.wrap(new DatabaseProductCatalog(), ProductCatalog.class); System.out.println(catalog.findName(7)); System.out.println(catalog.findName(7)); System.out.println(catalog.findName(3)); }}(database query for 7) Earbuds Earbuds (database query for 3) Notebook
What this code does
- Only the logic in the handler changed: the proxy looks up a cache key and calls the real method on a miss.
- The second
findName(7)prints no database line, which is what@Cacheabledoes in Spring.
The caching proxy checks a cache first and calls the real method only on a miss. The async proxy hands the call to a thread pool and returns at once. They share the same traps: no effect on self-invocation or private methods. They also need switching on, with @EnableCaching and @EnableAsync on a configuration class.
Next step
Check your understanding
12 quick questions