🍃 Spring Boot Intermediate

What is Spring AOP (Aspect-Oriented Programming)?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

AOP (Aspect-Oriented Programming) is a programming paradigm that separates cross-cutting concerns (logging, security, transactions, caching) from core business logic. Spring AOP uses dynamic proxies or CGLib to intercept method calls. Core concepts: Aspect: a module encapsulating cross-cutting concern (e.g., logging aspect); Join Point: a point in program execution where an aspect can be applied — in Spring AOP, always a method execution; Advice: action taken at a join point: @Before, @After, @AfterReturning, @AfterThrowing, @Around; Pointcut: expression selecting join points where advice is applied; Weaving: linking aspects to objects. Example — logging aspect: @Aspect @Component public class LoggingAspect { private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class); @Around("execution(* com.example.service.*.*(..))") public Object logExecutionTime(ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); try { Object result = pjp.proceed(); // execute the method log.info("{} executed in {}ms", pjp.getSignature(), System.currentTimeMillis() - start); return result; } catch (Throwable t) { log.error("Exception in {}: {}", pjp.getSignature(), t.getMessage()); throw t; } } @AfterThrowing(pointcut = "within(@org.springframework.stereotype.Service *)", throwing = "ex") public void logException(JoinPoint jp, Exception ex) { log.error("Service exception at {}: {}", jp.getSignature(), ex.getMessage()); } }. @EnableAspectJAutoProxy: enable AOP (auto-enabled by Spring Boot). Common uses: @Transactional, @Cacheable, @Async, @Secured, method-level logging, performance monitoring.

Pro Tip

This topic has Spring Boot-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.