Proxy

Intent
Put a stand-in with the same interface in front of an object to control access to it and add work before and after every call, without the client noticing.
Application
Booking a spot in a class is two writes that succeed or fail together. See how a proxy adds the transaction without touching your service, and why @Transactional is exactly that.
AthleteBookingControllerManualTxBookingServiceDatabase

The athlete sends POST booking to BookingController, which calls ManualTxBookingService, highlighted in red, which talks to the database.

The diagram doesn't change. ManualTxBookingService stays highlighted in red as the place where the transaction code is repeated.

TxBookingProxy and PlainBookingService appear, both implementing BookingOperations, highlighted together with the proxy. The controller calls the proxy and the proxy calls the real service.

The diagram doesn't change. TxBookingProxy stays highlighted, now as the code you'd have to repeat for every service.

The Spring context appears. Between the controller and BookingService sits the proxy Spring generates, highlighted together with the context. BookingService talks to the database.

Packets travel the chain: POST booking from the athlete to the controller, book() to the proxy, BEGIN · book() from the proxy to BookingService and INSERT + UPDATE to the database; finally ROLLBACK · 409 travels back from the proxy to the controller. The proxy is highlighted.

bookPair() reaches the proxy and moves on to BookingService, highlighted: both internal book() calls happen inside the real object, never going back to the proxy.

Inside the Spring context, ProxyFactory, highlighted, sends getProxy() to the proxy, also highlighted, which wraps BookingService.

Final view: the athlete, the controller, Spring's proxy, BookingService and the database inside the Spring context.

Step 1 of 9

One booking, two writes

Booking a spot in the 18:00 class is two changes in the database: insert the booking and take one free spot.

They have to go together. If the class is already full, the booking can't be left half-done, so you need a transaction. The manual version opens, commits and rolls it back by hand inside the service itself.

Step 2 of 9

And again, in every method

Cancelling a booking is two writes as well: delete the booking and give the spot back. So cancel() repeats the same ceremony: open, try, commit, catch, roll back.

Every new method copies it again, and forgetting one rollback in one catch is enough to leave the database inconsistent.

Step 3 of 9

A stand-in with the same face

The Proxy pattern pulls the two apart:

  • BookingOperations is the contract: book(sessionId, athlete).
  • PlainBookingService implements it with business logic only, not a single transaction line.
  • TxBookingProxy implements it too: it opens the transaction, delegates to the real service and commits or rolls back.

If the controller depends on BookingOperations, you hand it the proxy instead of the service and it can't tell the difference.

Step 4 of 9

One proxy per service

It works, and the service is finally clean. But look at the cost:

  • You need one proxy class per interface, with a wrapper method for every method.
  • The transaction code is still repeated; it just lives in the proxies now.
  • If tomorrow you also want to time calls or check permissions, that's another layer of proxies.

Step 5 of 9

@Transactional, and Spring writes the proxy

That's exactly what Spring does. You write the service with its business logic and one annotation: @Transactional.

At startup Spring sees the annotation and does not register your BookingService as is, but a generated proxy that wraps it (in the debugger you'll see a class like BookingService$$SpringCGLIB$$0). That's what the controller receives.

Step 6 of 9

A booking when the class is full

Follow the request:

  1. The athlete sends POST /api/sessions/1/bookings?athlete=Ana.
  2. The controller calls book() on the proxy, which opens a transaction and calls the real service.
  3. The service inserts the booking and tries to take a spot. With 0 left, it throws ClassFullException.
  4. The proxy sees the exception and rolls back: the inserted booking is gone and the API answers 409.

The API also guards its input: an empty name or one longer than 80 characters gets a 400, and booking the same class twice gets a 409.

Step 7 of 9

Watch out for this

A proxy only intercepts calls that reach it. bookPair() has no @Transactional and calls this.book() twice.

Those calls go straight to the real object without passing through the proxy, so there's no transaction. If the second booking fails because the class filled up, the first booking's row stays… and so does the second one, inserted before the spots were checked.

Step 8 of 9

Spring already does it for you

@Transactional is just one case. The same mechanism powers @Cacheable, @Async, @PreAuthorize, @Retryable… and Spring Data repositories, which are proxies of an interface you never implemented.

Underneath sits ProxyFactory: you give it an object and an interceptor that decides what happens before and after, and it hands you the proxy.

Step 9 of 9

Recap

You started with manual transactions in every method, moved to a hand-written proxy and ended up with one annotation:

  • The service only holds business logic.
  • The proxy, generated by Spring, opens, commits or rolls back the transaction.
  • The client never knows, because it gets the proxy with the same face as the service.
  • Watch out for this, private and final, which bypass the proxy.

Cheatsheet →

Code

ManualTxBookingService.java

public Booking book(long sessionId, String athlete) {
    TransactionStatus status = tx.getTransaction(new DefaultTransactionDefinition());
    try {
        repo.insertBooking(sessionId, athlete);
        if (!repo.takeSpot(sessionId)) {
            throw new ClassFullException(sessionId);
        }
        tx.commit(status);
        return new Booking(sessionId, athlete);
    } catch (RuntimeException | Error e) {
        tx.rollback(status);
        throw e;
    }
}

ManualTxBookingService.java

public void cancel(long sessionId, String athlete) {
    TransactionStatus status = tx.getTransaction(new DefaultTransactionDefinition());
    try {
        repo.deleteBooking(sessionId, athlete);
        repo.releaseSpot(sessionId);
        tx.commit(status);
    } catch (RuntimeException | Error e) {
        tx.rollback(status);
        throw e;
    }
}

TxBookingProxy.java

public class TxBookingProxy implements BookingOperations {
    private final BookingOperations target;
    private final PlatformTransactionManager tx;

    public TxBookingProxy(BookingOperations target, PlatformTransactionManager tx) {
        this.target = target;
        this.tx = tx;
    }

    @Override
    public Booking book(long sessionId, String athlete) {
        TransactionStatus status = tx.getTransaction(new DefaultTransactionDefinition());
        try {
            Booking booking = target.book(sessionId, athlete); // delegate to the real subject
            tx.commit(status);
            return booking;
        } catch (RuntimeException | Error e) {
            tx.rollback(status);
            throw e;
        }
    }
}

TxBookingProxy.java

public class TxBookingProxy implements BookingOperations {
    private final BookingOperations target;
    private final PlatformTransactionManager tx;

    public TxBookingProxy(BookingOperations target, PlatformTransactionManager tx) {
        this.target = target;
        this.tx = tx;
    }

    @Override
    public Booking book(long sessionId, String athlete) {
        TransactionStatus status = tx.getTransaction(new DefaultTransactionDefinition());
        try {
            Booking booking = target.book(sessionId, athlete); // delegate to the real subject
            tx.commit(status);
            return booking;
        } catch (RuntimeException | Error e) {
            tx.rollback(status);
            throw e;
        }
    }
}

BookingService.java

@Transactional
public Booking book(long sessionId, String athlete) {
    requireValidName(athlete);
    if (!repo.sessionExists(sessionId)) {
        throw new UnknownSessionException(sessionId);
    }
    repo.insertBooking(sessionId, athlete);
    if (!repo.takeSpot(sessionId)) {
        throw new ClassFullException(sessionId); // RuntimeException: the proxy rolls back
    }
    return new Booking(sessionId, athlete);
}

BookingServiceTest.java

// what Spring injected is not BookingService itself but a proxy around it
assertThat(AopUtils.isAopProxy(bookings)).isTrue();

assertThatThrownBy(() -> bookings.book(1, "Ana")).isInstanceOf(ClassFullException.class);

// the INSERT ran, the exception rolled it back: no half-made booking left
assertThat(BoxDb.bookings(jdbc)).isZero();

BookingService.java

/** ⚠ Deliberate pitfall for the lesson: no @Transactional here, and this.book() skips the proxy. */
public void bookPair(long sessionId, String athlete, String friend) {
    this.book(sessionId, athlete); // a plain Java call on the real object,
    this.book(sessionId, friend);  // so neither call runs in a transaction
}

SpringDoesItTooTest.java

ProxyFactory factory = new ProxyFactory(real);
factory.addAdvice((MethodInterceptor) call -> {
    log.add("begin");                 // open the transaction
    try {
        Object result = call.proceed(); // the real object does its job
        log.add("commit");
        return result;
    } catch (RuntimeException e) {
        log.add("rollback");            // undo, then let the error through
        throw e;
    }
});
return (Scoreboard) factory.getProxy();

BookingService.java

@Transactional
public Booking book(long sessionId, String athlete) {
    requireValidName(athlete);
    if (!repo.sessionExists(sessionId)) {
        throw new UnknownSessionException(sessionId);
    }
    repo.insertBooking(sessionId, athlete);
    if (!repo.takeSpot(sessionId)) {
        throw new ClassFullException(sessionId); // RuntimeException: the proxy rolls back
    }
    return new Booking(sessionId, athlete);
}

Quiz

1. Spring injects a BookingService with a @Transactional method. What does the controller actually get?

2. bookPair() has no @Transactional and calls this.book(), which does, twice. What happens?

3. What sets a Proxy apart from a Decorator, if both wrap another object with the same interface?

4. You wrap an object that implements an interface with ProxyFactory. What kind of proxy does Spring create?

Cheatsheet →

Run it