Spring AOP and BeanPostProcessor: proxies, pointcuts and advice order
Spring AOP runs on proxies created by a BeanPostProcessor: aspects, pointcuts, the five advice types and their order measured on Spring 7, several aspects with @Order, how AspectJ differs, BeanPostProcessor versus BeanFactoryPostProcessor, and why a bean injected into a BPP loses its proxy.
On this page
@Transactional, @Async, @Cacheable and your own logging aspect all run through a proxy: this post covers who creates it, when, which advice goes first, and why an aspect "doesn't run". Read the proxy and bean lifecycle parts of IoC and Dependency Injection first.
1. The problem
OrderService.placeOrder() calls this.audit(), and both have @Timed. The dashboard shows timings for placeOrder, but audit shows 0 calls, with not a single error line.
2. Key idea
Spring does not change your class. It puts a proxy in front of the bean: other beans call the proxy, which runs the advice and then calls the real object. Calls inside the real object (this.x()) skip the proxy.
| Term | Meaning |
|---|---|
| Aspect | an @Aspect class holding pointcuts and advice |
| Pointcut | which methods: execution(* com.shop..*Service.*(..)), @annotation(Timed) |
| Advice | what runs: @Before, @AfterReturning, @AfterThrowing, @After (like finally), @Around |
| Proxy | Boot uses CGLIB (a runtime subclass) for every bean by default |
2.1 With several aspects, who wraps whom?
The smaller @Order goes in first and comes out last, so it wraps outermost. Without it the order is undefined.
- Authorization: outermost, so a rejected request opens no transaction.
- Retry: outside
@Transactional, so each attempt is a new transaction. @Transactional,@Cacheable: lowest precedence by default, innermost.
2.2 Aspect or BeanPostProcessor?
A BPP runs for each bean at creation and may return a different object. The AOP proxy creator is itself a BPP.
| Need | Use when | Don't use when |
|---|---|---|
@Around/@AfterReturning aspect |
logging, timing, audit, retry around methods | you must intercept internal calls or private methods |
| Custom BPP | registering every bean with a custom annotation in a registry | setup for one bean: use @PostConstruct |
| AspectJ weaving | many real self-invocation cases | ordinary business apps: Spring AOP is enough |
3. In Java
@Aspect @Component @Order(2)
public class TimingAspect {
@Around("@annotation(com.shop.Timed)")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long t0 = System.nanoTime();
try {
return pjp.proceed(); // forget return: the caller gets null
} finally {
log.info("{} {}µs", pjp.getSignature().getName(), (System.nanoTime() - t0) / 1000);
}
}
}
// order.placeOrder() -> "placeOrder 812µs"
// this.audit() inside -> no line at allFixing self-invocation: move audit to another bean. Self-injecting @Lazy self works but hides the design. Other languages: NestJS interceptors and Python decorators do the same job without the proxy trap.
A bean injected into a BPP loses its aspects
Spring creates BPPs before ordinary beans. If a BPP (especially a PriorityOrdered one) takes a service in its constructor, the service is created before the proxy creator and is never wrapped. @Transactional, @Async and aspects all silently do nothing.
The only sign is one WARN line: Bean 'auditService' ... is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying).
Fix: declare BPPs as @Bean static, don't inject business beans; if needed, use ObjectProvider<T> and call it while processing beans.
4. Working with AI
Give the AI: writing the aspect and a test proving it runs (count calls, assert AopUtils.isAopProxy(bean)).
Check in AI-written code:
-
@AroundreturnsObjectand doesreturn pjp.proceed(). - No
@Transactional/@Timedmethod is called throughthis. - A retry aspect has a smaller
@Orderthan transactions, with a test that fails the first call. - Pointcuts are narrow; no
execution(* *(..)). - The startup log has no "not eligible for auto-proxying".
5. Exercises
Exercise 1: Predict the order
SecurityAspect @Order(1) has only @Around. TimingAspect @Order(2) has @Around, @Before, @AfterReturning, @After. Another bean calls orderService.placeOrder(), which calls this.audit(). Write the printed lines in order. What if you swap the @Order values?
Solution to Exercise 1
[1] security around: before
[2] timing around: before
[2] timing before
[2] timing afterReturning
[2] timing after (finally)
[2] timing around: after
[1] security around: afteraudit() prints nothing because it goes through this. Swapping @Order: the [2] block moves outside and [1] sits next to the method; the order inside each aspect stays the same.
Exercise 2: Retry "added" but still failing
An AI adds a hand-written @Retryable aspect, with no @Order, to a @Transactional method that often deadlocks. The log is still full of UnexpectedRollbackException. Explain and fix.
Solution to Exercise 2
Without @Order, retry shares the lowest precedence with @Transactional, so who wraps whom is arbitrary. Here retry sits inside the transaction: the second attempt runs on a transaction already marked rollback-only, and commit throws UnexpectedRollbackException.
Fix: @Order(Ordered.HIGHEST_PRECEDENCE) on the retry aspect, so each attempt opens a new transaction. Test it with a repository that throws a deadlock on the first call and succeeds on the second.
Summary
- Spring AOP works through proxies;
this.method()skips the aspect. - One aspect:
@Around→@Before→ method →@AfterReturning→@After. - The smaller
@Orderwraps outermost; retry goes outside@Transactional. - The proxy creator is a BPP; don't inject business beans into a BPP.
Read more: IoC and Dependency Injection.
Self-compiled notes from official documentation and hands-on practice.
Practice interview questions on this topic
- How do the Proxy and Decorator patterns differ? Which one does Spring AOP use?
- What is AOP in Spring? In what order do advice types run, and which aspect runs first when several match?
- How do JDK dynamic proxies and CGLIB proxies differ? Which does Spring Boot use by default?
- What are the steps of a bean's lifecycle? How do BeanPostProcessor and BeanFactoryPostProcessor differ?
- What are the @Transactional pitfalls: self-invocation, checked exceptions, readOnly and timeout?
All OOP & Design questions →All Spring Boot questions →All Transactions & Locking questions →
Comments
Community rules