liveBook · Manning

Interceptor

As explained in Spring Start Here, Second Edition

An aspect is a modular unit in aspect-oriented programming that intercepts selected program operations and applies cross-cutting behavior.

Logging, permission checks, and transaction handling can appear in many methods without being part of their main job. An aspect separates such supporting logic from business code and applies it to selected method calls. This can reduce duplication, but unnecessary aspects can make an application harder to maintain. section 6.0 section 6.5

In Spring AOP, an aspect intercepts calls to selected methods and can run logic before, after, or instead of the method. The selected object must be a bean managed by the Spring context. Spring supplies a proxy that intercepts calls and manages the aspect logic around the real object. section 6.1 section 6.5

Figure 6.3 Weaving an aspect. Instead of giving you a reference to the real bean, Spring gives you a reference to a proxy object, intercepts the method calls, and manages the aspect logic.

The proxy stands between the caller and the real bean, providing a place to apply the aspect logic. section 6.1

To define a Spring aspect, identify these pieces:

  • The aspect class contains the supporting logic. Mark it with @Aspect and also make an instance a Spring bean; the annotation alone is not enough. section 6.5
  • A pointcut expression selects the methods to intercept. It is supplied as the value of an advice annotation. section 6.5
  • Advice specifies how the logic relates to the intercepted call. Spring provides @Around, @Before, @After, @AfterThrowing, and @AfterReturning. section 6.5

Logging a service call

An @Around advice can read the method name and arguments from a ProceedingJoinPoint, log them, call proceed(), and then log and return the result. The caller receives the service result while the logging stays outside the service’s main logic. section 6.2.2

Listing 6.12 Obtaining the method name and parameters in the aspect logic
@Aspect
public class LoggingAspect {
 
  private Logger logger = Logger.getLogger(LoggingAspect.class.getName());
 
  @Around("execution(* com.example.services.*.*(..))")
  public Object log(ProceedingJoinPoint joinPoint) 
    throws Throwable {
 
    String methodName =                           #A
      joinPoint.getSignature().getName();         #A
    Object [] arguments = joinPoint.getArgs();    #A
 
    logger.info("Method " + methodName +   #B
        " with parameters " + Arrays.asList(arguments) +
        " will execute");
 
    Object returnedByMethod = joinPoint.proceed();    #C
 
    logger.info("Method executed and returned " + returnedByMethod);
 
    return returnedByMethod;  #D
  }
}

Follow proceed() to see where the intercepted method runs between the two log messages. section 6.2.2

An aspect can also pass different arguments to proceed(), return a different value, or handle or throw an exception. These capabilities give it control over the call, so use them carefully. section 6.2.2 section 6.5

Several aspects can form a chain around one method. Order matters: if a security aspect rejects a call before a logging aspect runs, that logging aspect cannot record the rejected call. Use @Order to specify an execution order when needed. section 6.3 section 6.5

Transactions behind the scenes

A method marked @Transactional is intercepted by a Spring-configured aspect, which applies transaction logic. By default, a runtime exception must escape the method for the aspect to see it and trigger rollback; catching it inside the method prevents the aspect from seeing that exception. section 13.2 section 13.3

How Spring Start Here, Second Edition covers it

How deep it goes
Explains proxy-based interception, advice configuration, argument and result changes, and ordered execution chains.
Examples
Uses service-call logging, security and logging chains, and a transactional money transfer.
What it assumes
Assumes Java development experience while teaching Spring and framework foundations from zero.
What you can do after
Apply it via Spring AOP to intercept service methods and control supporting behavior around their execution.
How it connects
Connects aspects with pointcuts, advice, Spring beans, proxies, transactions, and security.

Also explained in

Compare how 5 books explain interceptor →

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.