Sub topic 10
Before, after and around: the advice types
This chapter assumes you can write an @Aspect and a pointcut expression, as covered in the previous chapters, and that you know Spring wraps beans in proxies. Here you will learn the five advice types, when each one runs, and what each one can and cannot change.
What advice is
Advice is the code an aspect runs at a join point. In Spring AOP a join point is always a method execution on a Spring bean. The advice type decides when your code runs relative to that method.
| Annotation | Runs | Can see the result | Can stop the call | Can change the result |
|---|---|---|---|---|
| `@Before` | before the method | no | only by throwing | no |
| `@AfterReturning` | after normal return | yes, via `returning` | no | no |
| `@AfterThrowing` | after an exception | the exception, via `throwing` | no | no |
| `@After` | after either outcome, like `finally` | no | no | no |
| `@Around` | around the whole call | yes | yes | yes |
Use the weakest advice that does the job. A @Before that logs is harder to get wrong than an @Around that logs, because it cannot forget to call the target or swallow an exception.
All five advice types in one aspect
The example below uses a named pointcut and one advice method of each type. It needs spring-context and aspectjweaver on the classpath.
package com.example.demo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
class AccountService {
public int withdraw(int balance, int amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient funds");
}
return balance - amount;
}
}
@Aspect
class LifecycleAspect {
@Pointcut("execution(* com.example.demo.AccountService.*(..))")
void accountOps() {}
@Around("accountOps()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around: enter " + pjp.getSignature().getName());
try {
return pjp.proceed();
} finally {
System.out.println("around: exit " + pjp.getSignature().getName());
}
}
@Before("accountOps() && args(balance, amount)")
public void before(JoinPoint jp, int balance, int amount) {
System.out.println("before: " + jp.getSignature().getName()
+ " balance=" + balance + " amount=" + amount);
}
@AfterReturning(pointcut = "accountOps()", returning = "result")
public void afterReturning(int result) {
System.out.println("afterReturning: " + result);
}
@AfterThrowing(pointcut = "accountOps()", throwing = "ex")
public void afterThrowing(IllegalArgumentException ex) {
System.out.println("afterThrowing: " + ex.getMessage());
}
@After("accountOps()")
public void after(JoinPoint jp) {
System.out.println("after: " + jp.getSignature().getName() + " finished");
}
}
@Configuration
@EnableAspectJAutoProxy
class DemoConfig {
@Bean AccountService accountService() { return new AccountService(); }
@Bean LifecycleAspect lifecycleAspect() { return new LifecycleAspect(); }
}
public class Main {
public static void main(String[] args) {
try (var ctx = new AnnotationConfigApplicationContext(DemoConfig.class)) {
AccountService service = ctx.getBean(AccountService.class);
System.out.println("result: " + service.withdraw(100, 30));
System.out.println("---");
try {
service.withdraw(10, 50);
} catch (IllegalArgumentException e) {
System.out.println("caller saw: " + e.getMessage());
}
}
}
}The first call prints:
around: enter withdraw
before: withdraw balance=100 amount=30
afterReturning: 70
after: withdraw finished
around: exit withdraw
result: 70The second call replaces afterReturning with afterThrowing: Insufficient funds. The exception still reaches the caller.
The execution order
The diagram shows the successful path through the proxy.
Within one aspect class, Spring 5.2.7 and later orders advice by precedence: @Around, @Before, @After, @AfterReturning, @AfterThrowing. The first in that list runs first on the way in and last on the way out. That is why after prints after afterReturning but before the end of around.
Details for each type
@Before
If a @Before method throws, the target is never called. This makes it a natural place for argument checks or authorization. The args(balance, amount) clause binds the arguments to the advice parameters. It also narrows the match to methods whose arguments have those types.
@AfterReturning
The returning attribute binds the return value to the parameter named in the attribute. It also acts as a filter. If the parameter is declared as String, the advice runs only for methods that return a String. A void method matches only when the parameter is Object, and the value will be null. Changing the object's fields is possible, but you cannot replace the returned reference. Use @Around for that.
@AfterThrowing
The throwing attribute works like returning. Declaring IllegalArgumentException ex restricts the advice to that exception type and its subclasses. The advice observes the exception and cannot swallow it. The exception continues to the caller afterwards.
@After
@After runs in both the success and the failure case, like a finally block. It cannot see the return value or the exception. Use it for cleanup.
@Around
@Around advice receives a ProceedingJoinPoint, which has proceed() and proceed(Object[] args). The advice controls the call:
- It may skip
proceed()entirely, for example to return a cached value. - It may pass different arguments with
proceed(newArgs). - It must return the value that the caller should receive. Returning
nullfrom anintmethod causes an error at the proxy. - It must declare
throws Throwableand rethrow what it does not handle. Catching an exception and returning normally hides the failure from@AfterThrowingadvice that runs inside it, and from the caller.
Common errors
- Forgetting to return
pjp.proceed()in@Around. The caller then receivesnullor a failure. - Using
@Afterwhen you meant@AfterReturning.@Afteralso runs when the method fails. - Expecting
@AfterReturningto replace the result. It cannot. - Binding the wrong parameter names. The names in
returning,throwingandargs(...)must match the advice method parameters exactly. - Mixing up
JoinPointandProceedingJoinPoint. Only@Aroundcan use the latter.
Exercise
In the aspect above, withdraw(10, 50) is called. List, in order, the lines printed by the advice, and say what the caller receives.
Show answer
The output is "around: enter withdraw", "before: withdraw balance=10 amount=50", "afterThrowing: Insufficient funds", "after: withdraw finished", "around: exit withdraw". There is no afterReturning line, because the method did not return normally. The finally in the around advice runs, and the exception is not caught, so the caller receives the IllegalArgumentException.
Exercise
You want to add a cache so that a service method is skipped when a result is already stored. Which advice type do you need, and why can't the other four do it?
Show answer
Use @Around. It is the only type that can decide not to call proceed() and return a different value. @Before can only stop the call by throwing, and @AfterReturning, @AfterThrowing and @After run after the target and cannot replace the result.