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)

ApplicationContextAthletePaymentControllerPaymentService (proxy)PaymentService@Order(1) outer@Around@Before@AfterReturning@AfterThrowing@After

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 a finally
  • @Around + ProceedingJoinPoint.proceed(): wraps the call, can change arguments, result and exceptions
  • @Order(n) (or Ordered) 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 @After runs after @AfterReturning/@AfterThrowing (finally semantics)
  • Lower @Order value = higher precedence = first on the way in and last on the way out
  • @Around must return Object and return the result of proceed()
  • @Around can call proceed() 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 JoinPoint can be the first parameter of any advice; ProceedingJoinPoint, only in @Around

Exam traps

  • If an @Around doesn't return what proceed() gives, the caller gets null (or an error if the type is primitive)
  • If an @Around doesn't call proceed(), the real method never runs
  • @AfterThrowing doesn't swallow the exception: it keeps propagating; recovering requires @Around
  • The parameter type of @AfterThrowing/@AfterReturning filters: if it doesn't match, the advice doesn't run
  • If a @Before throws, neither the method nor that aspect's @After* advice runs

← AOP: advice types · Run it