Sub topic 12
Controlling the order of aspects
This chapter assumes you can write an @Aspect with @Around advice and know that Spring applies advice through a proxy. It covers what happens when several pieces of advice match the same method, and how to make that order predictable.
Why order matters
A single join point can match several aspects. A bean might be wrapped by a security check, a timing aspect, a retry aspect and a transaction. The order of these changes behavior:
- A timing aspect outside the transaction measures commit time. Inside, it does not.
- A retry aspect outside the transaction starts a fresh transaction per attempt. Inside, it retries within one transaction that may already be marked rollback-only.
- A security check should usually run before anything expensive.
If you declare no order, Spring does not guarantee one. It may look stable on your machine and change after a refactor or a different bean registration order.
Ordering between aspects
Give each aspect an order value with @Order on the class, or implement org.springframework.core.Ordered. A lower number means higher precedence.
Higher precedence means the aspect is outermost. On the way in, the highest-precedence aspect runs first. On the way out, the order reverses, like nested method calls.
package com.example.order;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
class OrderedService {
public String hello() {
System.out.println("hello");
return "done";
}
}
@Aspect
@Component
@Order(1)
class AspectA {
@Around("execution(* com.example.order.OrderedService.hello(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("A before");
try {
return pjp.proceed();
} finally {
System.out.println("A after");
}
}
}
@Aspect
@Component
@Order(2)
class AspectB {
@Around("execution(* com.example.order.OrderedService.hello(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("B before");
try {
return pjp.proceed();
} finally {
System.out.println("B after");
}
}
}
@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.example.order")
class OrderConfig {
}
public class OrderDemo {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(OrderConfig.class)) {
ctx.getBean(OrderedService.class).hello();
}
}
}Running it prints:
A before
B before
hello
B after
A afterAspectA has order 1, so it is the outer layer. AspectB sits inside it, and the target method is at the center.
Where the order value can go
@Orderon the aspect class works.Ordered.getOrder()works too. Use it when the value must be computed or configurable.@Orderon an advice method has no effect. Ordering applies to whole aspects.- An aspect with no order gets
Ordered.LOWEST_PRECEDENCE, which makes it the innermost layer. When two aspects tie, the relative order is undefined.
Ordering inside one aspect
Advice methods in the same @Aspect class that match the same join point follow fixed rules. Since Spring Framework 5.2.7, the precedence from highest to lowest is:
| Advice type | Relative position |
|---|---|
| `@Around` | Outermost. Runs first on the way in. |
| `@Before` | Runs before the target, inside `@Around`. |
| `@After` | Declared third, but behaves as "after finally". |
| `@AfterReturning` | Runs only on normal return. |
| `@AfterThrowing` | Runs only when an exception is thrown. |
Two details trip people up:
@Afterhas finally semantics. In practice it runs after any@AfterReturningor@AfterThrowingadvice from the same aspect, even though it ranks above them.- Two advice methods of the same type in one aspect have undefined order. If you need a sequence, put them in separate aspect classes and give each its own
@Order. Or merge them into one@Aroundmethod, where the code order is explicit.
Ordering relative to @Transactional
@Transactional is advice too, added by a transaction advisor. Its default order is Ordered.LOWEST_PRECEDENCE. Your aspects with a smaller number therefore wrap the transaction, and aspects with the default order tie with it.
You can change the transaction order with @EnableTransactionManagement(order = ...). More often you set your own aspect's order around it:
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
// Outside the transaction: each retry gets a new transaction.
@Order(Ordered.LOWEST_PRECEDENCE - 100)
class RetryAspect { /* @Around advice that calls pjp.proceed() in a loop */ }
// Inside the transaction: runs with the transaction already open.
// Order must be greater than the transaction advisor's order, which
// is already the maximum by default, so change the transaction order instead:
// @EnableTransactionManagement(order = 100)The rule to remember: the number decides who is outer. If a transaction must wrap your aspect, give the transaction a lower number than your aspect.
Checking the order you got
Do not trust a guess. Write a test like the demo above that records the order of calls, or enable debug logging for org.springframework.aop. You can also inspect the advisors on a proxy by casting it to Advised and calling getAdvisors(). They are listed outermost first.
Exercise
A class has two @Order aspects. LoggingAspect has @Order(5) and SecurityAspect has @Order(1), and both use @Around on the same method. Which runs first on the way in, and which finishes last on the way out?
Show answer
SecurityAspect (order 1) runs first on the way in because a lower number means higher precedence. It also finishes last on the way out, since it is the outer layer and the order reverses when returning.
Exercise
One aspect class defines two @Before methods that match the same method, and the output depends on their order. How do you make the order reliable?
Show answer
Order between two advice methods of the same type in one aspect is undefined. Move them into two separate aspect classes with distinct @Order values, or merge them into one method (or one @Around) where the code order is explicit.
Exercise
A RetryAspect should start a new database transaction on every attempt. Should it have higher or lower precedence than the transaction advisor, and what does that mean for the order number?
Show answer
Higher precedence, so it wraps the transaction. Its order number must be lower than the transaction advisor's order. The default transaction order is Ordered.LOWEST_PRECEDENCE, so a value such as Ordered.LOWEST_PRECEDENCE - 100 works.