An advice annotation tells Spring AOP when aspect logic should run around an intercepted method. It pairs that timing with an AspectJ pointcut expression that selects method executions. section 6.2.4
Choose the simplest annotation that fits the job:
- @Before runs aspect logic before the intercepted method. section 6.2.4
- @AfterReturning runs after a successful return and can receive the returned value. section 6.2.4
- @AfterThrowing runs when the method throws an exception and can receive that exception. section 6.2.4
- @After runs after execution whether the method returns or throws. section 6.2.4
- @Around offers the most flexibility, including the ability to run logic before and after the method or instead of it. section 6.2.4
Unlike @Around, these alternatives do not receive a ProceedingJoinPoint or decide whether to delegate to the intercepted method. Their annotation determines when that method runs. Prefer the least powerful option that keeps the implementation simple. section 6.2.4
Listing 6.20 Using the @AfterReturning annotation
@Aspect
public class LoggingAspect {
private Logger logger = Logger.getLogger(LoggingAspect.class.getName());
@AfterReturning(value = "@annotation(ToLog)", #A
returning = "returnedValue") #B
public void log(Object returnedValue) { #C
logger.info("Method executed and returned " + returnedValue);
}
}See an @AfterReturning example that logs the method’s returned value. section 6.2.4
