TL;DR
Proxy, Decorator and Adapter already run your Spring Boot app — @Transactional, @Cacheable, HandlerAdapter. Real code, the built-ins, and the traps.
Three of the most-used patterns in a Spring Boot codebase are the ones you never write: Proxy, Decorator, and Adapter. Every @Transactional method runs behind a proxy. Every @Cacheable call is intercepted before your code executes. Every controller method is invoked through an adapter. And when you do need one of these patterns yourself, the framework already has a version — the question is whether to use the built-in, write your own, or stop and use an annotation instead.
This article covers all three structural patterns with real code in Spring Boot 4.2 (Spring Framework 7.1, Java 17 minimum): the proxy mechanics underneath Spring AOP, a hand-written decorator you can actually ship, and adapters at the framework boundary. The short version up front: let the framework proxy framework concerns, write a decorator when the behaviour is yours, and put an adapter at every boundary where two APIs refuse to speak the same language.
Proxy: the invisible wrapper around every annotated bean
The Proxy pattern gives a caller a stand-in object with the same type as the real one, so the stand-in can add behaviour — open a transaction, check a cache, retry a failure — before delegating to the target. In Spring Boot you almost never write a proxy yourself, because the container creates them for you. The moment you put @Transactional, @Cacheable, @Async, or @Retryable on a bean, the object other beans receive is not your class. It is a proxy of your class, and your method runs one layer down.
@Service
public class OrderService {
private final OrderRepository orders;
public OrderService(OrderRepository orders) {
this.orders = orders;
}
@Transactional
public Order placeOrder(Cart cart) {
Order order = orders.save(new Order(cart));
// ... charge, notify, reserve stock ...
return order;
}
}Nothing in this code opens a transaction. The proxy does: it begins the transaction, calls your method, commits on success, and rolls back on a runtime exception. The same mechanism powers @Cacheable (the proxy checks the cache and may never call your method at all) and @Async (the proxy hands the call to a task executor and returns immediately).
How Spring builds the proxy
Spring AOP creates one of two proxy types, and the distinction explains most of the confusing behaviour people hit in production:
In a Spring Boot application, class-based (CGLIB) proxies are the default — Boot has set proxyTargetClass=true since 2.0 — so @Transactional on a concrete class works without an interface. In plain Spring Framework, the interface-based JDK proxy is still the default, which is why the same code can behave differently outside Boot. The Spring AOP proxying documentation covers both, including the rule that CGLIB cannot proxy final classes or final methods: mark a @Transactional method final and the annotation silently does nothing, because the subclass cannot override it.
You can also write your own advice. A timing aspect is the honest version of "just add logging everywhere":
@Aspect
@Component
public class TimingAspect {
private static final Logger log = LoggerFactory.getLogger(TimingAspect.class);
@Around("execution(* com.example.orders..*(..))")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try {
return pjp.proceed();
} finally {
log.info("{} took {} ms", pjp.getSignature().getName(),
(System.nanoTime() - start) / 1_000_000);
}
}
}Spring AOP is proxy-based, not bytecode weaving: the advice runs only when a call passes through the proxy. That is the whole of the most famous Spring trap.
The self-invocation trap
A call from one method of a bean to another method of the same bean never passes through the proxy, because this is the target, not the proxy:
@Service
public class OrderService {
public void placeAndNotify(Cart cart) {
placeOrder(cart); // direct call — NO transaction, NO cache
notifyCustomer(cart);
}
@Transactional
public Order placeOrder(Cart cart) { /* ... */ }
}placeOrder runs here with no transaction at all — the annotation is present, the code compiles, and the database writes commit one by one instead of atomically. Spring's own transaction annotation documentation calls this out explicitly: in proxy mode, only external method calls that come in through the proxy are intercepted, and self-invocation bypasses it. The fixes, in order of preference: call the method through an injected reference to the same bean (inject OrderService into itself, or better, split the two methods into separate beans so the call genuinely crosses a bean boundary), or switch to AspectJ load-time weaving if the codebase genuinely needs self-invocation to be intercepted — a heavyweight answer that most teams should not reach for first. The same trap applies to @Cacheable and @Async: a self-invoked @Async method runs synchronously, on the caller's thread, with no error and no warning.
When to reach for a proxy yourself
Almost never directly. The framework's proxies cover transactions, caching, async execution, retry, and security — and the moment you hand-roll a proxy you own the lifecycle of something the container already manages. The exception is a genuinely cross-cutting concern that no annotation covers, and then the answer is an @Aspect like the timing example above, not a ProxyFactory in application code. If you find yourself creating a ProxyFactoryBean in 2026, you are almost certainly re-implementing an annotation.
Decorator: wrap the bean, don't fork it
Where the Proxy is framework-owned, the Decorator is yours. The Decorator pattern wraps an object with another object of the same type, adding behaviour while leaving the original untouched. The shape in Spring Boot is a bean that takes the bean it decorates in its constructor, marked @Primary so the container injects the wrapper wherever the interface is requested:
@Service
@Primary
public class TimedPaymentGateway implements PaymentGateway {
private final PaymentGateway delegate;
public TimedPaymentGateway(@Qualifier("stripePaymentGateway") PaymentGateway delegate) {
this.delegate = delegate;
}
@Override
public PaymentResult charge(Payment payment) {
long start = System.nanoTime();
try {
return delegate.charge(payment);
} finally {
Metrics.record("payments.charge",
(System.nanoTime() - start) / 1_000_000);
}
}
}The caller sees a PaymentGateway. The decorator sees the same interface, adds timing, and delegates. Nothing in the original gateway changes, nothing in the caller changes, and the wrapper is trivially testable: pass a fake delegate in the constructor and assert the metric was recorded. Stack decorators the same way — a retry decorator around a timing decorator around the real gateway — and each layer stays small enough to read in one screen. That is the whole discipline: one decorator, one concern.
The decorators Spring already ships
You have been using framework decorators all along, which is worth knowing before you write your own:
TransactionAwareDataSourceProxy wraps a DataSource so getConnection() returns the connection already bound to the current transaction instead of opening a new one. Without it, code that borrows a connection directly bypasses the transaction the proxy opened.ContentCachingRequestWrapper wraps the servlet request so the body can be read more than once — the standard fix for a filter that needs to log the request body before the controller reads it.DelegatingFilterProxy is a servlet filter that delegates to a Spring bean of the same name, which is how Spring Security's filter chain plugs into the servlet container without the container knowing about Spring at all.The pattern in all three is the same as the hand-written one above: same type in, same type out, one added behaviour, delegation for everything else. The anti-pattern is the decorator that stops delegating — a wrapper that re-implements half the interface, or one that swallows the delegate's exceptions and returns a default. A decorator that changes the contract is not a decorator; it is a fork wearing a costume, and the next reader will trust the interface and be wrong.
Adapter: make two interfaces talk
The Adapter pattern translates one interface into another so two components that were never designed together can work together. Unlike Proxy and Decorator, the Adapter changes the type — that is the point. It lives at boundaries: your code on one side, a library, a legacy system, or a framework contract on the other.
Suppose a legacy billing client speaks its own dialect — a method that takes a map and throws a checked exception your domain code should never see:
// Legacy client: cannot be changed, speaks its own language
public class LegacyBillingClient {
public Map<String, Object> billCustomer(Map<String, Object> request)
throws BillingException { /* ... */ }
}The adapter presents your domain's interface and hides the legacy one:
@Component
public class BillingClientAdapter implements PaymentGateway {
private final LegacyBillingClient legacy;
public BillingClientAdapter(LegacyBillingClient legacy) {
this.legacy = legacy;
}
@Override
public PaymentResult charge(Payment payment) {
Map<String, Object> request = Map.of(
"customerId", payment.customerId(),
"amountCents", payment.amount().minorUnits(),
"currency", payment.amount().currency());
try {
Map<String, Object> response = legacy.billCustomer(request);
return new PaymentResult((String) response.get("receiptId"),
PaymentStatus.valueOf((String) response.get("status")));
} catch (BillingException e) {
throw new PaymentFailedException("Legacy billing rejected the charge", e);
}
}
}Two translations happen here and both matter. The data is translated (your Payment becomes their map, their map becomes your PaymentResult), and the error model is translated (their checked BillingException becomes your unchecked domain exception). An adapter that only does the first half leaks the adapted API into your codebase — the moment a caller catches BillingException, the boundary has failed.
The adapters Spring already ships
HandlerAdapter is the reason your controllers can return anything — a String, a ResponseEntity, a ModelAndView — and Spring MVC still knows how to invoke the method and render the result. Each handler type gets an adapter that translates it into the dispatcher's common contract; the HandlerAdapter javadoc is the interface that makes the whole of Spring MVC pluggable.CacheManager is an adapter over cache providers: your code calls cache.get(key) and the same code works against Caffeine in memory, Redis over the network, or a ConcurrentHashMap in tests. Swapping providers is a configuration change, not a code change, because the adapter owns the translation.HttpMessageConverter adapts between Java objects and wire formats — Jackson for JSON, JAXB for XML — so a controller returns a record and the framework decides the bytes.RestClient, the HTTP client introduced in Spring Framework 6.1, adapts the JDK HttpClient (and other engines) behind a fluent API, so your code never touches the underlying transport.The anti-pattern to avoid is the adapter that grows a second job. An adapter translates; it does not validate business rules, retry, or cache. The moment it does, it has become a service with a misleading name, and the next team to swap the underlying provider will find business logic hiding in the translation layer.
Head-to-head: Proxy vs Decorator vs Adapter
| Pattern | Same type? | Who writes it? | The question it answers | The Spring Boot way |
|---|---|---|---|---|
| Proxy | Yes | The framework | How do I add a cross-cutting concern without touching the code? | @Transactional, @Cacheable, @Async, custom @Aspect |
| Decorator | Yes | You | How do I add behaviour I own to one specific bean? | @Primary wrapper bean delegating to the @Qualifier original |
| Adapter | No | You | How do I make two incompatible interfaces work together? | A @Component translating at the boundary; HandlerAdapter, CacheManager built in |
The table hides the decision that actually matters in practice. Proxy and Decorator look alike — both wrap an object of the same type — but the ownership is the difference: the proxy belongs to the framework and applies to every bean with the annotation, while the decorator belongs to you and applies to one bean. If the behaviour is a framework concern, use the annotation and let the proxy do it. If the behaviour is yours and specific to one bean, write the decorator. If the types don't match, neither applies — write an adapter.
Architecture decision: structural patterns in Spring Boot
@Transactional, @Cacheable, @Async) for all framework concerns; hand-written @Primary decorators for per-bean behaviour we own; adapters at every external boundary. Never hand-roll a proxy, and never let a self-invocation carry a transactional or cached method.@Transactional badly and puts transaction semantics in application code where no reviewer expects them.final methods, advice ordering — and code review has to catch a @Transactional method called from inside its own bean. Decorators add one more bean per wrapped interface, which is visible in the application context and in stack traces.Recommendation
For a new Spring Boot service, adopt three rules and enforce them in review. First, framework concerns get annotations — @Transactional for the unit of work, @Cacheable for the cache, @Async for the background call — and nobody writes a proxy by hand. Second, behaviour that belongs to one specific bean gets a decorator: a @Primary wrapper with a @Qualifier delegate, one concern per wrapper, full delegation for everything else. Third, every external system gets an adapter at the boundary that translates both the data and the error model, so no legacy exception or foreign data shape ever reaches your domain code.
For an existing service, the migration is a code-review habit, not a project. The highest-value check is the self-invocation audit: search for @Transactional, @Cacheable, and @Async methods, and check whether any of them is called from another method in the same bean. Each one found is a real bug — a transaction that never opened, a cache that never filled, an async call that ran synchronously — and the fix is usually moving one method to a second bean. After that, look for the hand-rolled wrappers: a service that opens its own transactions with a TransactionTemplate in three places, or a client that catches a library exception in five controllers, is a proxy or an adapter waiting to be named.
When NOT to use these patterns
ProxyFactory for transactions or caching is a worse version of @Transactional and @Cacheable, with none of the ordering guarantees and all of the maintenance.@Async as a performance fix. Making a slow call asynchronous does not make it fast; it moves the slowness to a thread pool where it is harder to observe. Fix the slow call, or admit the work is genuinely background work.@Cacheable will do. The framework's cache abstraction handles eviction, key generation, and conditional caching; a hand-written cache inside a decorator re-implements all three, usually with one of them wrong.Proxy, Decorator, and Adapter are not patterns you choose from a catalogue — they are the three shapes wrapping already takes in a Spring Boot application, and the framework has already chosen two of them for you. Your job is to recognise which shape you are looking at, use the built-in where it exists, and spend your own code only where the behaviour is genuinely yours: the decorator around one bean, and the adapter at the boundary. For the patterns that decide what gets created in the first place, our creational patterns guide covers the Factory, Builder, and Singleton the container already implements — and if you are still deciding which Spring Boot line to build on, start with what's new in Spring Boot 4.2. For the broader question of how these wrapped services fit into the system's overall shape, our modular monolith vs microservices guide carries the architecture decision these patterns sit inside.
Why This Matters
Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.
Trade-offs to Consider
Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.
When NOT to Use This
Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.
Decision Framework
Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.