Video in progress

In a large codebase, is it better to handle cross-cutting concerns with AOP or with explicit composition (decorators, interceptors)?

For things that are the same everywhere and don't affect business logic (tracing, metrics, transaction boundaries), AOP is convenient. For things that change behavior (retry, caching, permission checks), I prefer explicit composition: whoever reads the code should see what is happening.

📖 Answer

AOP's strength and its danger are the same: the code is invisible. Someone reading a @Cacheable method may not realize it is sometimes never called. When annotations pile up, this becomes a serious problem.

The problems I've seen on large teams:

  • Aspect order. @Transactional, @Retryable, @Cacheable and the team's own @Audited aspect on one method. Which one is outermost? If retry is inside the transaction, it retries a transaction that has already rolled back and gets an UnexpectedRollbackException. Unless @Order is set explicitly everywhere, the order is accidental.
  • Broad pointcuts. With execution(* com.acme..*Service.*(..)), someone names a class Service and falls into the aspect without knowing it.
  • Self-invocation. Proxy-based AOP doesn't work on internal calls, and every new developer rediscovers this.
  • Debugging. 15 lines of CGLIB and interceptor frames in the stack trace.

So my rule is this:

AOP/annotations are for things that are observable but don't change behavior: @Observed/tracing, metrics, putting context into the MDC. Transactions belong here too, because @Transactional is a standard everyone understands.

Explicit composition is for things that change semantics:

PaymentClient client = Decorators.ofSupplier(() -> raw.charge(req))
    .withCircuitBreaker(cb)
    .withRetry(retry)
    .decorate();

or RestClient/WebClient interceptors, HandlerInterceptor, Spring Security filters. Here the order is visible in the code and tested separately.

At the team level: keep the number of your own aspects to a minimum, give each one an owner and documentation, and write pointcuts by explicit annotation, not by package name. A pointcut by annotation is opt-in; one by name is accidental.