# Spring AOP: Aspects, Advice and Proxies

> What is AOP in Spring? Explain aspect, advice, pointcut, join point, and how Spring implements it.

Canonical: https://www.internhack.in/learn/interview/spring-boot-interview/spring-aop-basics
Last updated: 2026-11-28

Difficulty: Advanced

## Question

What is AOP in Spring? Explain aspect, advice, pointcut, join point, and how Spring implements it.

## Answer

Some concerns cut across your whole application: logging every service call, measuring execution time, checking permissions, managing transactions. If you write that code inside each method you end up with tangled, repetitive classes where business logic is buried under boilerplate. Aspect-Oriented Programming lets you write that cross-cutting behaviour once, in one place, and apply it to many methods declaratively. Think of a security guard at a building entrance: instead of every office checking your ID, one guard handles it for everyone.

The vocabulary is a standard interview drill. An aspect is the module holding the cross-cutting logic, a class annotated @Aspect. A join point is a point in execution where an aspect could apply; in Spring AOP that is always a method execution. A pointcut is an expression selecting which join points to match, for example every public method in classes annotated @Service. Advice is the code that runs at those points, and its type determines when: @Before runs before the method, @After runs after regardless of outcome, @AfterReturning runs after normal return, @AfterThrowing runs after an exception, and @Around wraps the call, deciding whether and how to proceed. Weaving is the process of linking aspects to targets.

Spring implements AOP at runtime with proxies. For each bean matched by some pointcut, the container creates a proxy object wrapping the real one. If the bean implements an interface, Spring can use a JDK dynamic proxy; otherwise, and by default in Boot, it uses CGLIB, which subclasses your class. Callers receive the proxy, which runs the advice chain and then delegates to the real method. Because it relies on proxies, Spring AOP has limits: only method calls on Spring beans through the proxy are intercepted, so self-invocation is not advised, and private, static, or final methods cannot be intercepted with CGLIB. This is exactly the same reason @Transactional, @Async, and @Cacheable have their self-invocation pitfall, because they are all AOP-based. If you need full power, such as intercepting field access or constructors, use AspectJ with compile-time or load-time weaving, which Spring can integrate but is rarer.

Use @Around carefully. You receive a ProceedingJoinPoint and must call proceed() and return its result, otherwise the target method never runs. Always rethrow exceptions instead of swallowing them, and measure time in a finally block. Keep aspects fast, because they sit on hot paths, and avoid heavy logging of sensitive arguments such as passwords.

Real examples where AOP earns its place: audit logging of admin actions, timing and metrics on service methods, retry logic, rate limiting, request tracing, and custom method-level authorisation. Boot includes the dependency via spring-boot-starter-aop, and auto-configuration enables @EnableAspectJAutoProxy for you. In an interview, wrap up by saying AOP improves separation of concerns but can hide behaviour, so keep aspects few, well named, and documented.

## Code examples

### A timing and logging aspect

```
@Aspect
@Component
@Slf4j
public class PerformanceAspect {

    // pointcut: every public method of any @Service class
    @Pointcut("within(@org.springframework.stereotype.Service *)")
    public void serviceMethods() { }

    @Around("serviceMethods()")
    public Object time(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.nanoTime();
        try {
            return pjp.proceed();                       // run the real method
        } finally {
            long ms = (System.nanoTime() - start) / 1_000_000;
            log.info("{} took {} ms", pjp.getSignature().toShortString(), ms);
        }
    }

    @AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
    public void onError(JoinPoint jp, Exception ex) {
        log.warn("{} failed: {}", jp.getSignature().getName(), ex.getMessage());
    }
}
```

Around advice wraps every service method without touching business code. Note it must call proceed() and rethrow exceptions.

## Key points

- Spring AOP is proxy-based and limited to method execution on Spring beans.
- CGLIB is the default proxy type in Boot; JDK proxies need interfaces.
- Self-invocation, private and final methods are not advised.
- @Transactional, @Async and @Cacheable are all built on this same mechanism.

## Common follow-up questions

- What is the difference between Spring AOP and AspectJ?
- JDK dynamic proxy versus CGLIB?
- How would you implement retry using AOP?

## Interview tips

- Define all five terms in one clean pass; interviewers tick them off.
- Link AOP to the @Transactional self-invocation pitfall.

## Concepts covered

AOP, Aspect, Pointcut, Proxy

Previous: [Spring Boot Actuator for Production Monitoring](https://www.internhack.in/learn/interview/spring-boot-interview/spring-boot-actuator) · Next: [Microservices with Spring Cloud: Service Discovery and API Gateway](https://www.internhack.in/learn/interview/spring-boot-interview/spring-cloud-discovery-gateway) · [All of Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)

## More Spring Boot questions

- [Circuit Breaker and Resilience4j](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circuit-breaker-resilience4j)
- [Testing: @SpringBootTest vs @WebMvcTest vs @DataJpaTest](https://www.internhack.in/learn/interview/spring-boot-interview/spring-testing-slices)
- [Testing Controllers with MockMvc and Mockito](https://www.internhack.in/learn/interview/spring-boot-interview/spring-mockito-mockmvc-testing)
- [Circular Dependencies in Spring and How to Fix Them](https://www.internhack.in/learn/interview/spring-boot-interview/spring-circular-dependencies)
- [Spring vs Spring Boot: What Problem Does Boot Solve?](https://www.internhack.in/learn/interview/spring-boot-interview/spring-vs-spring-boot)
- [Inversion of Control and Dependency Injection Explained](https://www.internhack.in/learn/interview/spring-boot-interview/spring-ioc-dependency-injection)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Spring Boot](https://www.internhack.in/learn/interview/spring-boot-interview)
