Spring AOP and proxies
- AOP
- aspect-oriented programming
Senior Frequently asked 5 min
On this page
The question
What are an aspect, advice and a pointcut in Spring AOP?
30-second answer
An aspect is a class holding a cross-cutting concern, such as logging or timing. A pointcut is an expression selecting methods. Advice is the code that runs there: @Before, @AfterReturning, @AfterThrowing, @After or @Around. A join point is one matched method call. Spring applies all this through a proxy at run time, and it is how @Transactional works.
Understand it
The advice chain around a method
Step by stepThe caller holds a proxy, not your object. The pointcut matched pay, so the proxy builds a chain of advice around it.
View as text
Nested boxes: a proxy around aspect A, around aspect B, around the pay method. The current layer is highlighted, and a log below lists each piece of advice as it runs.
The caller holds a proxy, not your object. The pointcut matched pay, so the proxy builds a chain of advice around it.
The aspect with the lowest @Order is outermost. Its @Around runs first, and decides whether to call proceed().
The next aspect, @Order(2), starts its @Around. Advice nests like layers, so what enters first leaves last.
Inside that aspect, @Before runs after @Around starts. It cannot stop the call, except by throwing.
proceed() finally reaches your method. It knows nothing about the aspects around it.
The method returned, so @AfterReturning runs. If it had thrown, @AfterThrowing would run here instead.
@After runs either way, like finally. Then the inner @Around finishes.
The outer @Around finishes last, and may change the result or swallow an exception. The caller gets the value.
Nested boxes: a proxy around aspect A, around aspect B, around the pay method. The current layer is highlighted, and a log below lists each piece of advice as it runs.
The caller holds a proxy, not your object. The pointcut matched pay, so the proxy builds a chain of advice around it.
The aspect with the lowest @Order is outermost. Its @Around runs first, and decides whether to call proceed().
The next aspect, @Order(2), starts its @Around. Advice nests like layers, so what enters first leaves last.
Inside that aspect, @Before runs after @Around starts. It cannot stop the call, except by throwing.
proceed() finally reaches your method. It knows nothing about the aspects around it.
The method returned, so @AfterReturning runs. If it had thrown, @AfterThrowing would run here instead.
@After runs either way, like finally. Then the inner @Around finishes.
The outer @Around finishes last, and may change the result or swallow an exception. The caller gets the value.
Takeaway: Aspects nest around the target like layers: lowest @Order on the outside. Calls go in through @Around and @Before, and come back out through @After and @Around.
JDK proxy vs CGLIB
CompareA JDK proxy implements the same interface. It is not a PayImpl, so injecting or casting to the class fails. With no interface, Spring uses CGLIB instead.
View as text
A proxy box linked to what it is built from, above four rows: what it needs, whether injecting by class works, whether it is the Boot default, and what happens to a final method.
A JDK proxy implements the same interface. It is not a PayImpl, so injecting or casting to the class fails. With no interface, Spring uses CGLIB instead. Needs: An interface. Inject by class: BeanNotOfRequiredType. Boot default: No: opt in. final method: Advised as usual.
A CGLIB proxy is a generated subclass, the Boot default even when an interface exists. A final method cannot be overridden, so it runs on the proxy, with null fields. Needs: A non-final class. Inject by class: Works. Boot default: Yes. final method: Skips advice, null fields.
A proxy box linked to what it is built from, above four rows: what it needs, whether injecting by class works, whether it is the Boot default, and what happens to a final method.
A JDK proxy implements the same interface. It is not a PayImpl, so injecting or casting to the class fails. With no interface, Spring uses CGLIB instead. Needs: An interface. Inject by class: BeanNotOfRequiredType. Boot default: No: opt in. final method: Advised as usual.
A CGLIB proxy is a generated subclass, the Boot default even when an interface exists. A final method cannot be overridden, so it runs on the proxy, with null fields. Needs: A non-final class. Inject by class: Works. Boot default: Yes. final method: Skips advice, null fields.
Takeaway: JDK proxies implement an interface and CGLIB proxies subclass the class. Boot defaults to CGLIB, so the traps are final classes and final methods.
In code
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Timed {
}
@Aspect
@Component
class TimingAspect {
@Around("@annotation(timed)")
Object time(ProceedingJoinPoint call, Timed timed) throws Throwable {
long start = System.nanoTime();
try {
return call.proceed(); // forget this, and the method never runs
} finally {
long micros = (System.nanoTime() - start) / 1_000;
System.out.println(call.getSignature().getName() + " took " + micros);
}
}
}@Aspect
@Component
class AuditAspect {
@Pointcut("within(com.shop.service..*)")
void inServices() {
}
@AfterReturning("inServices() && @annotation(Audited)")
void record(JoinPoint call) {
System.out.println("audit " + call.getSignature());
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface Audited {
}@Aspect
@Component
class FailureLogger {
private static final Logger log = LoggerFactory.getLogger(FailureLogger.class);
@AfterThrowing(pointcut = "within(com.shop.service..*)", throwing = "e")
void logFailure(JoinPoint jp, RuntimeException e) {
log.error("{} failed: {}", jp.getSignature().toShortString(), e.getMessage()); // the exception still propagates
}
}Solve it
The audit aspect logs some calls and silently skips others
@Audited methods should each write an audit line. OrderService.place() is audited, but place() calling
this.reserve() writes nothing for reserve(), a private audited helper never logs, and a service built with new in
a batch job logs nothing at all.
- Recall the mechanism. Spring AOP wraps a bean in a proxy. Only a call that goes through the proxy can be advised.
- Self-invocation.
this.reserve()calls the target object directly and never passes the proxy. - Methods a proxy cannot override. CGLIB proxies subclass the bean, so
private,finalandstaticmethods are never intercepted. - No bean, no proxy. An object created with
newis not managed by Spring and has no proxy at all. - Fix and check. Move
reserve()to another bean, make it public and non-final, and inject the service. A test assertsAopUtils.isAopProxy(service)and one audit line per call.
@Service
class OrderService {
private final StockService stock; // another bean: calls go through its proxy
OrderService(StockService stock) { this.stock = stock; }
@Audited
public void place(Order order) { stock.reserve(order); }
}
@Service
class StockService {
@Audited
public void reserve(Order order) { /* public, not final: the proxy can intercept it */ }
}How to answer
- Spring AOP only intercepts method calls on beans, from outside.
@Aroundmust callproceed(), or the method never runs.- Use the weakest advice that does the job, such as
@Beforeover@Around. - Lowest
@Orderis the outermost aspect.
Common mistakes
- Thinking Spring AOP changes your class's bytecode, as compile-time AspectJ does.
- Forgetting
proceed(), or forgetting to return its value, in@Around.
Follow-up questions
What is the difference between a JDK (Java Development Kit) dynamic proxy and a CGLIB (Code Generation Library) proxy?
A JDK proxy implements the target's interfaces, so it is not an instance of the class. A CGLIB proxy is a generated subclass, so it needs a non-final class and overridable methods. Spring Framework alone prefers JDK proxies when an interface exists, while Spring Boot sets spring.aop.proxy-target-class=true, so CGLIB is the default. That is why injecting a concrete class works in Boot.
- With a JDK proxy, injecting by class fails with
BeanNotOfRequiredTypeException. - A class with no interface always gets CGLIB.
- Objenesis creates the subclass, so your constructor is not called twice.
What are the limits of proxy-based AOP?
Only calls that go through the proxy are advised. A self-call on this skips it. Private and static methods cannot be overridden, so they are not advised. A final method runs on the proxy object itself, whose fields are null, with no error at startup. A final class fails at startup. Objects you create with new have no proxy at all.
- Kotlin classes are final by default, and the
kotlin-springplugin opens them. - Advice applies to beans only, not to any Java object.
- AspectJ weaving removes these limits, with more tooling.
@Service
public class PayService {
private final Audit audit = new Audit();
@Timed
public final void pay() {
audit.log(); // NullPointerException through the proxy
}
} See it in the infographic: JDK proxy vs CGLIB See it in the infographic: The advice chain around a method
A final class matches a pointcut. What happens when the application starts?
Startup fails: CGLIB cannot subclass it, with "Cannot subclass final class". This failure is loud, unlike a final method, which is silently not advised. Remove final, or extract an interface and force JDK proxies. Records are final too, so they cannot be proxied this way, and they make poor beans for advice.
- The error comes from
AopConfigException, at bean creation. - A broad pointcut can catch a class you did not intend, so keep pointcuts narrow.
- JDK proxies do not need the class to be open, only an interface.
In what order does advice run inside one aspect?
@Around starts, then @Before, then the method, then @AfterReturning or @AfterThrowing, then @After, and @Around finishes last. That is the order since Spring Framework 5.2.7. Between aspects, the lower @Order value wraps the higher one.
Which built-in Spring features rely on AOP proxies?
@Transactional, @Cacheable, @Async, @Retryable and @PreAuthorize all do. They share the same limits, so a self-call skips each of them. When two apply to one method, their order matters: a retry should usually be outside the transaction, so each attempt gets a new one.
Check yourself
Show answers
- A: Correct. The lowest order is outermost. It starts first and finishes last, like the outer layer of an onion.
- B: Incorrect. B is inside A, so it finishes before A does.
- The order is random.: Incorrect. @Order defines it. Random order only applies when no order is set.
Show answers
- CGLIB: Correct. Boot sets proxy-target-class to true, so it subclasses even when an interface exists.
- JDK dynamic proxy: Incorrect. That is plain Spring Framework's preference. Boot overrides it.
- None, because aspects change the bytecode.: Incorrect. Spring AOP works at run time, through proxies, not through weaving.