Repaso
EspaƱol

What is Spring AOP (aspect-oriented programming) typically used for?

Options

  1. Writing the HTML templates for the views of an app
  2. Adding logging or security around methods without edits (Correct option)
  3. Compiling the project faster with fewer classes
  4. Storing the user sessions between two requests

Answer

Adding cross-cutting behavior such as logging, transactions, security or timing around methods without changing their code, using proxies

Why

Some concerns appear in many places (logging, transactions, security checks, metrics). Copying that code into every method clutters the logic.

AOP lets you define an aspect (advice) and where it applies (pointcut). Spring implements it with proxies that wrap your beans: @Transactional, @Cacheable, @Async and method security all work this way.

Because it is proxy-based, calls inside the same class are not intercepted (self-invocation).

@Aspect
@Component
public class TimingAspect {
    @Around("execution(* com.acme.service..*(..))")
    public Object time(ProceedingJoinPoint pjp) throws Throwable {
        long t = System.nanoTime();
        try { return pjp.proceed(); }
        finally { System.out.println(pjp.getSignature() + " took " + (System.nanoTime() - t) / 1_000_000 + " ms"); }
    }
}

Remember

AOP = reusable behavior around methods, implemented with proxies.

Key terms

Practice this question in Repaso