liveBook · Manning

Advice annotation

As explained in Spring Start Here, Second Edition

An advice annotation is a Spring AOP annotation that specifies when aspect logic runs relative to an intercepted method execution.

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

How Spring Start Here, Second Edition covers it

How deep it goes
Defines five timing options and their return, exception, and delegation behavior, with a logging example.
Examples
Demonstrates logging a method’s returned value with @AfterReturning.
What you can do after
Apply a suitable Spring advice annotation to run aspect logic before, after, on return, or on exception.
How it connects
Connects Spring AOP aspects with AspectJ pointcut expressions and intercepted method executions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.