Spring AOP and Proxies
Aspect-Oriented Programming adds cross-cutting behaviour such as logging, security, transactions and caching around methods without changing them. In Spring it works through proxies, which explains the famous self-invocation problem with @Transactional and @Async.
What you will learn
- Know the AOP terms: aspect, advice, pointcut, join point
- Write an @Around aspect
- Explain JDK dynamic proxies vs CGLIB
- Explain why self-invocation skips the proxy
Key concepts
Aspect, advice, pointcut
An aspect is a class of cross-cutting logic. Advice is what runs (@Before, @After, @AfterReturning, @AfterThrowing, @Around). A pointcut selects which methods it applies to.
Proxy
Spring wraps the bean in a proxy; callers get the proxy, which runs advice and then calls the real object. Interfaces can use JDK dynamic proxies; Spring Boot defaults to CGLIB subclass proxies.
Self-invocation
Calling this.otherMethod() inside the same bean goes straight to the object, not through the proxy, so @Transactional, @Async, @Cacheable and your aspects on otherMethod do not apply.
Step by step
A timing aspect
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)
public @interface Timed {}
@Aspect @Component
class TimingAspect {
@Around("@annotation(Timed)")
Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try {
return pjp.proceed();
} finally {
log.info("{} took {} ms", pjp.getSignature().toShortString(), (System.nanoTime() - start) / 1_000_000);
}
}
}Examples
The self-invocation trap
@Service
class OrderService {
public void placeAll(List<Order> orders) {
orders.forEach(this::place); // calls the real object: NO transaction per order
}
@Transactional
public void place(Order o) { ... }
}
// Fixes: move place() to another bean, inject the proxy (self-reference), or use TransactionTemplate.Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Write an aspect that logs every exception thrown from @Service classes.
- Prove the self-invocation problem with a test that checks TransactionSynchronizationManager.isActualTransactionActive().
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Why do @Transactional methods need to be public (historically) and not final?
Proxies intercept calls by overriding or delegating methods. CGLIB cannot override final methods, and before Spring 6 transactional advice only applied to public methods. Spring 6 also supports protected and package-private methods for class-based proxies.
Summary
AOP applies cross-cutting logic through proxies around beans; know the advice types and pointcuts, and remember that internal this-calls bypass the proxy and its annotations.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus