Sub topic 10
Before, after and around: the advice types
This chapter assumes you can write a Spring @Aspect, enable AOP, and read a basic pointcut expression such as execution(* com.example.service..*(..)). Advice is the code that runs at a matched join point. Spring offers five kinds, and they differ in when they run and what they can change.
The five advice types
| Annotation | Runs | Can it change the result? |
|---|---|---|
| `@Before` | Before the method | No. It can stop the call only by throwing an exception. |
| `@AfterReturning` | After a normal return | It can read the result but cannot replace it. |
| `@AfterThrowing` | After an exception | It can read the exception but cannot swallow it. |
| `@After` | After either outcome, like `finally` | No. |
| `@Around` | Wraps the call | Yes. It controls whether the method runs, its arguments and its result. |
Choose the weakest advice that does the job. A @Before that checks an argument is easier to read and harder to get wrong than an @Around that does the same thing.
One aspect with four advice methods
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LifecycleAspect {
@Pointcut("execution(* com.example.service..*(..))")
void serviceMethods() {
}
@Before("serviceMethods()")
public void before(JoinPoint jp) {
System.out.println("before " + jp.getSignature().toShortString());
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void afterReturning(JoinPoint jp, Object result) {
System.out.println("returned " + result);
}
@AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
public void afterThrowing(JoinPoint jp, Exception ex) {
System.out.println("threw " + ex.getClass().getSimpleName());
}
@After("serviceMethods()")
public void after(JoinPoint jp) {
System.out.println("finished " + jp.getSignature().toShortString());
}
}The @Pointcut method gives the expression a name, so each advice refers to it instead of repeating the string. The returning and throwing attributes bind the outcome to a parameter. Spring also uses the parameter type as a filter. Here afterThrowing only runs for an Exception, and an Error skips it. A typed returning parameter, such as String result, restricts the advice to methods that return that type.
Order of execution
For one call that succeeds, the order is @Around (before proceed), @Before, the target method, @AfterReturning, @After, then @Around (after proceed).
Common errors
- Putting
@Afterlogic that needs the result.@Afterhas no access to the return value. Use@AfterReturning. - Expecting
@AfterThrowingto handle the error. It runs and the exception keeps propagating. To recover, use@Aroundwith atry/catch. - Using
@Aroundwithout callingproceed(). The target method is silently skipped. - Using
@Aroundand returningvoidfrom the advice method. The caller then getsnullinstead of the real result.
Exercise
A service method returns a String. You want to log the returned value, but only when the method completes normally. Which advice type fits, and which attribute passes the value to your method?
Show answer
Use @AfterReturning with the returning attribute, for example @AfterReturning(pointcut = "serviceMethods()", returning = "result"), and add a matching result parameter to the advice method. It does not run when the method throws, and @After cannot see the value.
Exercise
An @Around advice calls pjp.proceed() inside a try block, catches Exception, logs it, and returns null. What happens to the caller, and what would @AfterThrowing have done differently?
Show answer
The caller receives null and never sees the exception, because the aspect swallowed it. @AfterThrowing would log the exception but let it keep propagating to the caller.