Cheatsheet

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.

Structure (UML)

AthleteSpring contextBookingControllerBookingService (proxy)30BookingServiceDatabase

Participants

  • Subject (BookingOperations in the hand-written version; in Spring, the BookingService class itself), the contract the real object and its proxy share
  • RealSubject (PlainBookingService or BookingService), which does the actual work
  • Proxy (TxBookingProxy or the one Spring generates), which opens the transaction, delegates and commits or rolls back
  • Client (BookingController), which talks to the proxy believing it's the service

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);
}

Pros

  • The service only holds business logic; the transaction lives elsewhere
  • The client doesn't change, because the proxy honours the same contract
  • With Spring, one annotation replaces a proxy class per service

Cons

  • The magic is invisible and hard to debug if you don't know there's a proxy
  • Internal calls (this.method()) bypass the proxy
  • Private or final methods can't be intercepted

← Proxy · Run it