Published

- 10 min read

Proxy Pattern in Java: How @Transactional Really Works

A stand-in with the same interface that controls access to the real object: by hand, in the proxies Spring builds for you, and the self-invocation trap that leaves half an order saved.

img of Proxy Pattern in Java: How @Transactional Really Works

Your interviewer asks: a debit card stands in for your bank account, but it checks your PIN and your limit before any money moves. Is that a Decorator?

If you said yes, that’s the trap. A decorator adds something to a call and always passes it on. The card decides whether the call happens at all: a wrong PIN, and the payment never reaches your account. Something that stands in for an object and controls access to it is the Proxy pattern. It is the question the Decorator post ended on.

Seven lines around every method

When you save an order, you write the order and then reserve its stock, and if the stock call fails, the order can’t stay saved. So the method opens a transaction, commits at the end, and rolls back on failure:

   public void save(Order o) {
  tx.begin();
  try {
    orders.insert(o);
    stock.reserve(o);
    tx.commit();
  } catch (RuntimeException e) {
    tx.rollback();
    throw e;
  }
}

Two lines do the work, and the other seven are plumbing. Every method that must be all-or-nothing carries the same seven lines, in every service, and the one method where someone forgets the rollback is the one that leaves half an order in the database.

The Proxy pattern

The Proxy pattern moves those lines into a stand-in. It has the same interface as your service, so callers can’t tell they’re holding something else, and it controls access to the real one: your method only runs inside a transaction, and the proxy decides whether its work is kept.

   class OrderServiceProxy
    extends OrderService {
  public void save(Order o) {
    tx.run(() -> real.save(o));
  }
}

tx.run holds the begin, commit and rollback lines from above, once. real is the actual OrderService, and save is back to its two lines of work. The proxy extends the service here because that is how Spring builds it, as you’ll see below; a hand-written proxy just as often implements the same interface as the real class.

The Gang of Four list a few kinds, by what the proxy controls. A virtual proxy creates the real object only when it’s first used, a protection proxy checks the caller’s rights, a remote proxy makes a call over the network look local, and a smart reference does extra work around each call, like this transaction. A cache in front of a slow service is the one most people build first.

Not a decorator, not an adapter

Proxy, Decorator and Adapter all hold another object and pass calls to it, so they look alike in code. Three questions tell them apart:

ProxyDecoratorAdapter
Same interface as the inner?YesYesNo: that’s the point
Can it stop the call?Yes: a wrong PIN, a cache hit, a rollbackNever: the inner object always runsNo: it translates every call
Who puts it there?Usually a framework, or the object’s own ownerThe code that stacks the wrappersYou, around a class you can’t edit
How many?Usually one, in front of the objectA stack of any depth, in any orderOne per mismatched interface

A transaction proxy always calls the real method, so it can look like a decorator. What makes it a proxy is that the container hands out only the proxy, the real method never runs outside a transaction, and the proxy decides whether the work is kept.

You already use it: Spring builds them

Spring builds these for you. Mark a method @Transactional, and every bean that asks for an OrderService gets a generated subclass that runs it inside a transaction. You never write the class: Spring creates it at startup with CGLIB.

A Spring Data repository goes one step further. You write an interface and never implement it:

   interface OrderRepository extends
    JpaRepository<Order, Long> {
  List<Order> findByStatus(
      String status);
}

What Spring hands you is a JDK dynamic proxy for that interface. It passes save and findById to Spring Data’s own SimpleJpaRepository, and answers findByStatus with a query it builds from the method’s name. Print the class of each bean and you see both kinds (Spring Boot 4.1.2, Spring Framework 7.0.10, from the code repo):

/CodeVxDev

ionicons-v5-d

proxy

./mvnw -pl structural/proxy spring-boot:run

13:10:52

The OrderService you get: OrderService$$SpringCGLIB$$0
The OrderRepository you get: jdk.proxy2.$Proxy102
save(lamp), called from outside: out of stock: lamp, saved orders: []
placeOrder(lamp), save() called from inside: out of stock: lamp, saved orders: [Order(lamp)]
fixed placeOrder(lamp), through OrderWriter: out of stock: lamp, saved orders: []

The two kinds work differently. A JDK dynamic proxy (java.lang.reflect.Proxy) implements interfaces, so it can only stand in for an interface. CGLIB generates a subclass, so it can stand in for a class, but only for the methods it can override. Plain Spring uses a JDK proxy when the bean implements an interface and CGLIB when it doesn’t; Spring Boot sets spring.aop.proxy-target-class=true, so your services get the subclass either way.

The same machinery is behind @Async, @Cacheable, @Retryable and @PreAuthorize, and Hibernate uses its own proxies for lazy relations. The last three lines of that output are the catch.

In production: a call from inside skips the proxy

Here is what catches people in production. placeOrder validates the order and then calls the transactional save, on the same class:

   class OrderService {
  public void placeOrder(Order o) {
    validate(o);
    save(o);
  }
  @Transactional
  public void save(Order o) {
    orders.insert(o);
    stock.reserve(o);
  }
}

A controller calls placeOrder on the proxy. placeOrder isn’t transactional, so the proxy passes the call to the real object, and inside it save(o) means this.save(o): the real object’s own method. The call never leaves the object, so the proxy never sees it and there is no transaction. The repository’s own save commits the order at once, the stock call fails, and the order stays saved without its stock. It’s called self-invocation, and it is one of the most common Spring questions in interviews.

The fix is to make the call leave the object. Move save into another class, and the call crosses that bean’s proxy:

   class OrderService {
  final OrderWriter writer;

  public void placeOrder(Order o) {
    validate(o);
    writer.save(o);
  }
}

OrderWriter is a separate bean that holds the @Transactional save. Here is all of it in one file you can run with java Proxy.java: a hand-written stand-in for the proxy Spring generates, with a stock call that fails. Through the proxy, order 2 is rolled back; from inside the class, order 3 stays saved; through the fix, order 5 is rolled back. The last lines are a real JDK dynamic proxy answering for an interface nobody implemented:

/CodeVxDev

ionicons-v5-d

proxy

java Proxy.java

13:10:52

save() called from outside, through the proxy:
    tx begin
    insert order-1
    reserve stock for order-1
    tx commit
    saved orders: [order-1]
the same, when the stock call fails: rolled back
    tx begin
    insert order-2
    tx rollback
    failed: out of stock for order-2
    saved orders: [order-1]
placeOrder() calls save() from inside: no transaction, the order stays saved
    insert order-3 (no transaction: saved at once)
    failed: out of stock for order-3
    saved orders: [order-1, order-3]
the same lines written by hand in every method:
    tx begin
    insert order-4
    tx rollback
    failed: out of stock for order-4
    saved orders: [order-1, order-3]
fix: save() moved to another bean, the call crosses its proxy
    tx begin
    insert order-5
    tx rollback
    failed: out of stock for order-5
    saved orders: [order-1, order-3]
an interface you never implement, answered by a proxy:
    proxy got findByStatus(PAID)
    result: [Order[id=order-1]]

Before you ship it

Other fixes for self-invocation

Moving the method into another bean is the fix to reach for first: it usually means the class was doing two jobs. When that split doesn’t make sense, there are three others, from most to least common:

  • TransactionTemplate for the one block that needs a transaction. No proxy is involved, so where the call comes from doesn’t matter:

       public void placeOrder(Order o) {
      validate(o);
      txTemplate.executeWithoutResult(s -> {
        orders.save(o);
        stock.reserve(o);
      });
    }
  • Inject the bean into itself, as a @Lazy field, and call self.save(o). It works, but a reader has to know why it’s there.

  • AspectJ weaving (@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)) changes the class’s bytecode instead of wrapping it, so calls from inside are covered too. It needs a weaving agent or a build plugin, which is why few teams use it.

Every proxy annotation has the same trap

Self-invocation isn’t about transactions. Anything Spring implements with a proxy is skipped by a call from inside: an @Async method runs on the caller’s thread, an @Cacheable method hits the database every time, and an @PreAuthorize method skips the permission check, which is the one that turns into a security bug.

final and private methods

The generated subclass can only intercept methods it can override. A final @Transactional method runs with no transaction: the call lands on the proxy object itself, whose fields are empty, so a method that uses one fails with a NullPointerException. A private method can only be called from inside anyway, so an annotation on it never does anything.

Hibernate’s lazy proxies

A @ManyToOne(fetch = LAZY) field holds a Hibernate proxy that runs its query the first time you touch it. Touch it after the transaction has ended, in a controller or a JSON serializer, and you get a LazyInitializationException. Load what the caller needs inside the transaction (a fetch join or an entity graph), or return a DTO.

The code repo has this pattern as a Maven module, the transaction lines by hand, the proxy written out, and the Spring version on a real database, with three of these pitfalls as tests: the call from inside and its fix, @Async from inside, and a final method. Browse it in structural/proxy on GitHub and run ./mvnw -pl structural/proxy test.

Spot it in LLD interviews

When callers should keep the same interface, but something has to happen before the real object is reached (load it, check a permission, look in a cache, cross the network, open a transaction), think Proxy:

LLD questionThe real objectWhat the proxy controlsKind
Service layerOrderServiceRuns it only inside a transactionSmart
Image viewerA large imageLoads it only when it is drawnVirtual
Document sharingA documentChecks the caller’s role firstProtection
Pricing serviceA slow price lookupAnswers repeated calls from a cacheCaching
Payment API clientA remote serviceMakes the network call for youRemote
Rate-limited APIAn expensive serviceCounts calls and refuses the extrasProtection
ORMA related entityQueries the database on first accessVirtual

The image viewer is the one interviewers ask most: a gallery shows a hundred thumbnails, and each full image is loaded only when someone opens it. The ImageProxy holds the file name, implements Image, and creates the real image on the first display(). The follow-up is usually “isn’t that just a decorator?”, and the answer is the table above: the proxy decides whether and when the real object exists, and the gallery never knows the difference.

When not to use it

If one method needs a check and nothing else ever will, an if at the top of that method is clearer than a stand-in. If the wrapper always passes the call on and only adds to it, it’s a decorator. If it changes the interface, it’s an adapter. And for transactions, caching and security in Spring, don’t write the proxy yourself: use the annotation, and remember where the call comes from.

/CodeVxDev

ionicons-v5-d

proxy

cat proxy.md

13:10:52

same interface, controls access
use: lazy, secure, cache, remote
watch: calls from inside skip it

The interview trap

You have to call a bank’s SDK, but its methods don’t match your payment interface, so you wrap it in a class that does. Is that a Proxy?

A. Yes, Proxy    B. No

Think about what a proxy keeps the same as the object behind it, and what this wrapper is for. Leave A or B as a

comment on the video; the next episode in this series answers it.