Cheatsheet
AOP: advice types
Key idea
An advice is an aspect's code, and its type decides when it runs relative to the method: before (`@Before`), after a normal return (`@AfterReturning`), after a throw (`@AfterThrowing`), always (`@After`) or wrapping it (`@Around`). Only `@Around` controls whether the method runs and what it returns.
Diagram (UML)
sequenceDiagram
participant C as PaymentController
participant O as OuterAspect «@Order(1)»
participant A as PaymentAspect «@Order(2)»
participant T as PaymentService «target»
C->>O: charge("Ana", 79)
O->>A: @Around in (outer)
A->>A: @Around in
A->>A: @Before (may throw to stop)
A->>T: proceed()
alt returns normally
T-->>A: receipt
A->>A: @AfterReturning(receipt)
else throws CardDeclinedException
T-->>A: exception
A->>A: @AfterThrowing(ex), still propagates
end
A->>A: @After (finally)
A->>A: @Around out
A-->>O: result
O-->>C: @Around out (outer)Key pieces
@Before: before; can only prevent the call by throwing an exception@AfterReturning(pointcut = …, returning = "r"): after a normal return; sees the result@AfterThrowing(pointcut = …, throwing = "ex"): after a throw; sees the exception but doesn't stop it@After: always, like afinally@Around+ProceedingJoinPoint.proceed(): wraps the call, can change arguments, result and exceptions@Order(n)(orOrdered) on the aspect class: precedence between aspects
PaymentAspect.java
@Around("charge()")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
trace.add("around in");
long start = System.nanoTime();
try {
return pjp.proceed(); // call the next advice / the target; RETURN its result
} finally {
trace.add("around out " + (System.nanoTime() - start >= 0));
}
}Remember for the exam
- Inside one aspect precedence is
@Around→@Before→@After→@AfterReturning→@AfterThrowing, but@Afterruns after@AfterReturning/@AfterThrowing(finallysemantics) - Lower
@Ordervalue = higher precedence = first on the way in and last on the way out @Aroundmust returnObjectand return the result ofproceed()@Aroundcan callproceed()zero, one or several times (retries) and with other arguments:proceed(args)- Advice parameters are bound by name with
args(...),returning,throwing,@annotation(param) - A
JoinPointcan be the first parameter of any advice;ProceedingJoinPoint, only in@Around
Exam traps
- If an
@Arounddoesn't return whatproceed()gives, the caller getsnull(or an error if the type is primitive) - If an
@Arounddoesn't callproceed(), the real method never runs @AfterThrowingdoesn't swallow the exception: it keeps propagating; recovering requires@Around- The parameter type of
@AfterThrowing/@AfterReturningfilters: if it doesn't match, the advice doesn't run - If a
@Beforethrows, neither the method nor that aspect's@After*advice runs