Question 15 · Section 5

What is AOP (Aspect-Oriented Programming)?

4. Static Pointcut -> faster than dynamic 5. Avoid state in aspects (Singleton!) 6. @Around -> do not forget pjp.proceed()

Language versions: English Russian Ukrainian

Junior Level

AOP is a way to add common functionality (logging, transactions) to many classes without changing their code.

Simple analogy: Imagine you want to record every call in a company. Instead of asking every employee to keep a log, you put automatic recording on all calls.

// Without AOP:
public void save() {
    log.info("Start");  // Repeated everywhere
    repository.save(entity);
    log.info("End");
}

// With AOP:
@LogExecution  // One annotation!
public void save() {
    repository.save(entity);
}

Why:

  • Removes code duplication
  • Business logic separate, infrastructure separate
  • Easy to enable/disable

Middle Level

Spring AOP vs AspectJ

  Spring AOP AspectJ
How Runtime proxy Bytecode modification
What can Only public methods Methods, fields, constructors
Self-invocation Does NOT work Works
Complexity Simple Complex setup

Spring AOP works only with Spring beans (calls through proxy). AspectJ works with any objects, as it is woven at bytecode level (compile-time or load-time weaving).

AOP Terms

Aspect               = cross-cutting logic module
Pointcut             = where to apply (expression)
Advice               = what to do (logic)
Join Point           = specific method

Advice Types

@Before         // Before method
@After          // After method (always)
@AfterReturning // After successful
@AfterThrowing  // On exception
@Around         // Instead of method (most powerful)

Aspect Example

@Aspect
@Component
public class LoggingAspect {

    @Around("@annotation(LogExecution)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        try {
            return pjp.proceed();  // Call original method
        } finally {
            long duration = System.currentTimeMillis() - start;
            log.info("Completed in " + duration + "ms");
        }
    }
}

Senior Level

Interceptor Chain

Method call -> ReflectiveMethodInvocation:
  1. SecurityInterceptor -> permission check
  2. TransactionInterceptor -> transaction
  3. CacheInterceptor -> cache
  4. LoggingAspect -> logging
  5. Target method -> your code

-> Each returns result or throws exception
-> Order determined by @Order

Performance

AOP overhead:
  -> Creating MethodInvocation object
  -> Going through interceptor list
  -> Reflection or direct call

-> ~1-5 microseconds per call
-> In Highload (1M RPS) -> noticeable!

Spring 6 + Virtual Threads

`synchronized` (keyword) in aspects -> Pinning of virtual threads!
-> Check if your aspects block system threads

Production Experience

Full example with Around without proceed() - in file [[16. What is aspect advice pointcut join point]].

Best Practices

  1. Spring AOP -> 95% of cases
  2. AspectJ -> private methods, fields
  3. @Order -> aspect ordering
  4. Static Pointcut -> faster than dynamic
  5. Avoid state in aspects (Singleton!)
  6. @Around -> do not forget pjp.proceed()

Summary for Senior

  • AOP = cross-cutting functionality without duplication
  • Spring AOP = proxy, AspectJ = bytecode
  • Interceptor Chain -> order via @Order
  • Overhead ~1-5 microseconds per call
  • Pinning -> careful with synchronized in aspects
  • pjp.proceed() -> required in @Around

Interview Cheat Sheet

Must know:

  • AOP = cross-cutting functionality (logging, transactions, cache) without code duplication
  • Spring AOP works via proxy at runtime; AspectJ - via bytecode modification
  • Key terms: Aspect (module), Pointcut (where), Advice (what), Join Point (specific method)
  • 5 Advice types: @Before, @After, @AfterReturning, @AfterThrowing, @Around
  • @Around - most powerful, but MUST call pjp.proceed()
  • Aspect order determined via @Order
  • Spring AOP: only public methods of Spring beans, self-invocation does NOT work
  • AOP overhead: ~1-5 microseconds per call, adds up in Highload

Common follow-up questions:

  • Why doesn’t Spring AOP work with private methods? -> Proxy only intercepts calls through proxy object, private methods are not accessible
  • When to choose AspectJ over Spring AOP? -> When you need private methods, fields, constructors, or self-invocation
  • @After vs @AfterReturning - what is the difference? -> @After = always (like finally), @AfterReturning = only on successful completion
  • What is ReflectiveMethodInvocation? -> Spring Pipeline, sequentially going through all interceptors

Red flags (DO NOT say):

  • “Spring AOP works with private methods” - does not work
  • “@Around without proceed() is acceptable” - method will not be called at all
  • “AOP adds milliseconds of overhead” - nanoseconds (1-5 microseconds)
  • “Aspect stores state in fields” - aspect = Singleton, not thread-safe

Related topics:

  • [[13. What is a proxy in Spring]]
  • [[14. When does Spring create a proxy]]
  • [[16. What is aspect advice pointcut join point]]
  • [[17. What does the Transactional annotation do]]