Video in progress

Junior 🌱 Spring

How do the @Before, @AfterReturning, @AfterThrowing, @After and @Around advice types differ?

When / What it can do — @Before: before the call / sees the arguments, can stop the call by throwing an exception; @AfterReturning: after a normal return / reads the result (returning = "result"); @AfterThrowing: when an exception is thrown / sees the exception, but can't "swallow" it; @After: always (like finally) /…

📖 Answer

Advice When What it can do
@Before before the call sees the arguments, can stop the call by throwing an exception
@AfterReturning after a normal return reads the result (returning = "result")
@AfterThrowing when an exception is thrown sees the exception, but can't "swallow" it
@After always (like finally) cleaning up resources
@Around instead of the call everything: timing, replacing the result, retrying
@Around("@annotation(uz.app.Timed)")
Object time(ProceedingJoinPoint pjp) throws Throwable {
    long t = System.nanoTime();
    try {
        return pjp.proceed();          // call the original method
    } finally {
        log.info("{}: {} ms", pjp.getSignature().getName(),
                 (System.nanoTime() - t) / 1_000_000);
    }
}

Which one should you use? The simplest one that does the job. If you only need logging, @Before or @AfterReturning. @Around is the most powerful, but it's easy to forget to call proceed() or to return the result, and then the original method doesn't run at all or the caller gets null.