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.
In the box
A payment at the box has a before, an after when it works, an after when it fails and a "whatever happens". Each moment has its advice. Learn the five of them, the order they run in, what each one can do and how to order several aspects.
AthletePaymentControllerManualPaymentService

The athlete sends POST payment to PaymentController, which calls charge() on ManualPaymentService, highlighted in red.

The proxy sits in front of PaymentService; below, @Before, highlighted, receives the athlete and amount arguments from the proxy.

@AfterReturning, @AfterThrowing and @After, highlighted to the right of the proxy. The receipt packet travels from the proxy to @AfterReturning.

@Around, highlighted on the left, receives proceed() from the proxy: it's the advice that decides whether and how the call continues.

Packets travel along the chain: POST payment to the controller, charge() to the proxy and from the proxy to the target, and receipt towards @AfterReturning.

@AfterThrowing and @After, highlighted: the CardDeclined packet travels from the proxy to @AfterThrowing and the exception goes on its way.

The outer aspect with @Order(1), highlighted on the left, receives the @Order(1) packet from the proxy: it wraps all the other advice.

In the GatewayClient proxy, RetryAspect, highlighted, calls proceed() three times; the gateway answers timeout, timeout and ok.

Final view: controller, proxy and PaymentService on top; below, the six advices, the incoming ones on the left and the outgoing ones on the right.

Step 1 of 9

Four moments around a payment

Charging at the box has several things around the logic:

  • Before: check the amount is positive.
  • If it works: record the receipt sent.
  • If it fails: raise an alert.
  • Whatever happens: mark the operation as finished.

ManualPaymentService does it with an if, a try, a catch and a finally in the method itself. And it would have to be repeated in every payment method.

Step 2 of 9

@Before: before the method

@Before runs before the real method is called. With args(athlete, amount) in the pointcut, Spring passes the arguments by name as advice parameters.

What it can and can't do:

  • It can read arguments and throw an exception. Throwing is the only way to prevent the call.
  • It can't change the arguments or the result.

Step 3 of 9

@AfterReturning, @AfterThrowing and @After

Three advice types for the way out:

  • @AfterReturning(returning = "receipt"): only if the method returns normally. It receives the result but can't replace it (it can mutate it if the object is mutable).
  • @AfterThrowing(throwing = "ex"): only if the method throws. The parameter type filters: with CardDeclinedException ex, other exceptions don't trigger it. The exception keeps propagating.
  • @After: always, success or failure, like a finally. It sees neither the result nor the exception.

Step 4 of 9

@Around: the most powerful

@Around wraps the call. It receives a ProceedingJoinPoint and decides:

  • Whether to call the method (pjp.proceed()), how many times and with which arguments (pjp.proceed(newArgs)).
  • What to return to the caller: proceed()'s result or something else.
  • What to do with exceptions: let them through, swallow them or change them.

That's why transactions, caching and metrics use it. The example times the call with a try/finally around proceed().

Step 5 of 9

A payment that works

POST /api/payments?athlete=Ana&amount=79. The test compares the trace with the exact order:

outer in → around in → before → target → afterReturning → after → around out → outer out.

Notice two things:

  • Within an aspect, @Around goes in before @Before.
  • @After comes after @AfterReturning. Since Spring 5.2.7, precedence within an aspect is @Around, @Before, @After, @AfterReturning, @AfterThrowing, but @After, being a finally, runs last on the way out.

Step 6 of 9

A payment that fails

Zoe's card is blocked and the method throws CardDeclinedException:

outer in → around in → before → target → afterThrowing → after → around out → outer out.

There's no afterReturning, and the exception reaches the controller, which answers 402. @AfterThrowing only watched.

Step 7 of 9

Several aspects: @Order

OuterAspect also has an @Around on charge(). With several aspects on the same method, the order is set by @Order on the aspect class (or by implementing Ordered):

  • Lower value = higher precedence = more outer: it goes in first and comes out last.
  • Without @Order, the order between aspects is undefined.

Step 8 of 9

@Around calls proceed() several times

The payment gateway is flaky: the first two calls out of every three time out. RetryAspect fixes it without touching GatewayClient:

  • It calls proceed() inside a loop.
  • If TransientGatewayException is thrown, it tries again, up to 3 times.
  • On the third failure, it rethrows the exception.

Whoever calls send() gets ok and never learns about the two failures. The test checks it by counting 3 real calls.

Step 9 of 9

Recap

  • @Before: before; prevents the call only by throwing.
  • @AfterReturning: after a normal return, sees the result. @AfterThrowing: after a throw, sees the exception and doesn't stop it. @After: always.
  • @Around: wraps; decides whether, how many times and what to return. Always return pjp.proceed().
  • Order: within an aspect, Around → Before → method → AfterReturning/AfterThrowing → After. Between aspects, @Order (lower = more outer).

Cheatsheet →

Code

ManualPaymentService.java

/** Before: every "moment" around the call is hand-written, in every method that needs it. */
public class ManualPaymentService {
    public String charge(String athlete, BigDecimal amount, List<String> log) {
        if (amount.signum() <= 0) throw new IllegalArgumentException("amount must be positive"); // before
        try {
            String receipt = "receipt:" + athlete + ":" + amount;
            log.add("sent " + receipt);                                    // after returning
            return receipt;
        } catch (RuntimeException e) {
            log.add("alert " + e.getMessage());                            // after throwing
            throw e;
        } finally {
            log.add("done");                                               // after (finally)
        }
    }
}

PaymentAspect.java

@Before("charge() && args(athlete, amount)")          // binds the arguments by name
public void validate(String athlete, BigDecimal amount) {
    trace.add("before");
    if (amount.signum() <= 0) {
        throw new IllegalArgumentException("amount must be positive"); // the only way to stop the call
    }
}

PaymentAspect.java

@AfterReturning(pointcut = "charge()", returning = "receipt")
public void sent(JoinPoint jp, String receipt) {      // only when the method RETURNS normally
    trace.add("afterReturning " + receipt);
}

@AfterThrowing(pointcut = "charge()", throwing = "ex")
public void alert(CardDeclinedException ex) {         // only for THIS exception type; it still propagates
    trace.add("afterThrowing " + ex.getMessage());
}

@After("charge()")
public void done() {                                   // always, like finally
    trace.add("after");
}

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));
    }
}

AdviceOrderTest.java

@Test
void aSuccessfulPayment() {
    payments.charge("Ana", new BigDecimal("79"));

    assertThat(trace.lines()).containsExactly(
        "outer in",                    // @Order(1) aspect wraps everything
        "around in", "before",         // inside one aspect: @Around, then @Before
        "target",
        "afterReturning receipt:Ana:79",
        "after",                       // "finally": after @AfterReturning / @AfterThrowing
        "around out true",
        "outer out");
}

AdviceOrderTest.java

@Test
void aDeclinedCard() {
    assertThatThrownBy(() -> payments.charge("Zoe", new BigDecimal("79")))
        .isInstanceOf(CardDeclinedException.class);    // @AfterThrowing does not swallow it

    assertThat(trace.lines()).containsExactly(
        "outer in", "around in", "before", "target",
        "afterThrowing card declined for Zoe",          // no afterReturning
        "after", "around out true", "outer out");
}

@Test
void aBeforeAdviceThatThrowsStopsTheCall() {
    assertThatThrownBy(() -> payments.charge("Ana", new BigDecimal("-5")))
        .isInstanceOf(IllegalArgumentException.class);

    assertThat(trace.lines()).doesNotContain("target")
        .containsExactly("outer in", "around in", "before", "around out true", "outer out");
}

OuterAspect.java

@Aspect
@Component
@Order(1) // lower value = higher precedence: first on the way in, last on the way out
public class OuterAspect {
    private final Trace trace;

    public OuterAspect(Trace trace) {
        this.trace = trace;
    }

    @Around("execution(* com.spring2learn.box.advice.PaymentService.charge(..))")
    public Object security(ProceedingJoinPoint pjp) throws Throwable {
        trace.add("outer in");
        try {
            return pjp.proceed();
        } finally {
            trace.add("outer out");
        }
    }
}

RetryAspect.java

@Aspect
@Component
public class RetryAspect {
    static final int MAX_ATTEMPTS = 3;

    @Around("execution(* com.spring2learn.box.advice.GatewayClient.send(..))")
    public Object retry(ProceedingJoinPoint pjp) throws Throwable {
        for (int attempt = 1; ; attempt++) {
            try {
                return pjp.proceed();                       // @Around may call proceed() several times…
            } catch (TransientGatewayException e) {
                if (attempt == MAX_ATTEMPTS) {
                    throw e;                                // …or swallow, replace or rethrow the exception
                }
            }
        }
    }
}

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));
    }
}

Quiz

1. Which advice type can prevent the method from running without throwing an exception and return another value instead?

2. An @Around calls `pjp.proceed();` but ends with `return null;`. The intercepted method returns a String. What does the caller get?

3. The method throws CardDeclinedException and there's an @AfterThrowing(throwing = "ex") with a CardDeclinedException parameter. What happens to the exception?

4. Within one aspect there are @Around, @Before, @AfterReturning and @After on the same method, which completes normally. In what order do they run?

5. OuterAspect has @Order(1) and PaymentAspect @Order(2), and both have an @Around on charge(). Which runs first on the way in?

6. In which advice can you declare a ProceedingJoinPoint parameter?

Cheatsheet → · Mock exam →

Run it