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)
classDiagram
direction LR
class BookingController {
<<Client>>
+book(sessionId, athlete) Booking
}
class BookingOperations {
<<Subject>>
+book(sessionId, athlete) Booking
}
class PlainBookingService {
<<RealSubject>>
}
class TxBookingProxy {
<<Proxy>>
+book(sessionId, athlete) Booking
}
BookingController --> BookingOperations
BookingOperations <|.. PlainBookingService
BookingOperations <|.. TxBookingProxy
TxBookingProxy --> PlainBookingService : targetParticipants
- 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