How does Spring AOP work? Explain JDK dynamic proxies vs CGLIB and the self-invocation problem.
Concepts
- Aspect: a module of cross-cutting behaviour (logging, metrics, transactions, security).
- Advice: what runs (
@Before,@AfterReturning,@AfterThrowing,@After,@Around). - Pointcut: where it runs (
execution(* com.shop..*Service.*(..)),@annotation(Audited)). - Join point: in Spring AOP, always a method execution on a Spring bean.
Proxy-based weaving
Spring AOP does not modify bytecode. In postProcessAfterInitialization it wraps the bean in a proxy that runs the advice chain and then calls the target.
- JDK dynamic proxy: implements the bean's interfaces; works only through interface methods.
- CGLIB proxy: generates a subclass at runtime; works without interfaces; cannot advise
finalclasses or methods, and private methods are never proxied. - Spring Boot defaults to CGLIB (
spring.aop.proxy-target-class=true).
Self-invocation
A call from one method of a bean to another method of the same bean uses this, the raw target, not the proxy. The advice on the inner method (transaction, cache, async, retry) silently does not run.
Fixes, best first:
- Move the method into a separate bean.
- Inject the bean into itself lazily (
@Lazyself-reference) or useAopContext.currentProxy()withexposeProxy = true; both work but are smells. - Use AspectJ compile-time or load-time weaving, which modifies bytecode and has no proxy limitation.
Example
@Aspect @Component
class TimingAspect {
private final MeterRegistry registry;
TimingAspect(MeterRegistry registry) { this.registry = registry; }
@Around("@annotation(timed)")
Object time(ProceedingJoinPoint pjp, Timed timed) throws Throwable {
Timer.Sample sample = Timer.start(registry);
try {
return pjp.proceed();
} finally {
sample.stop(registry.timer(timed.value(), "method", pjp.getSignature().getName()));
}
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
Why does @Transactional on a private method do nothing?
Proxies can only intercept calls that come through the proxy to methods it can override or implement. Private methods cannot be overridden by a CGLIB subclass and are never called through the proxy, so the annotation is ignored (no error). The same applies to final methods, and to @Async, @Cacheable and @Retryable.
When would you use AspectJ weaving instead of Spring AOP?
When you need join points Spring AOP cannot provide: self-invocation, private or final methods, field access, constructor execution, or objects not managed by Spring (for example applying @Configurable to JPA entities). The cost is a more complex build (the AspectJ compiler or a load-time weaving agent).