Spring AOP - Proxy, Pointcut, Advice

AOP (Aspect-Oriented Programming) pulls cross-cutting logic (logging, transactions, auth) out of business code. Spring AOP is proxy-based: Pointcut matches join points, Advice defines the enhancement. This article explains proxy, pointcut, and advice types with a reference table.

Overview

  • Proxy: Spring uses JDK dynamic proxy (for interfaces) or CGLIB (for classes). The proxy runs aspect logic before and after method calls.
  • Pointcut: Defines which methods are intercepted. E.g. @Around("execution(* com.example.service.*.*(..))").
  • Advice: Before, After, AfterReturning, AfterThrowing, Around. Around controls when the method runs and what it returns.
  • Aspect: @Aspect class with @Pointcut and @Before/@Around etc.

Example

Example 1: Declarative transaction

Java
@Transactional
public void createOrder(Order o) {
    // Transaction aspect starts/commits around the method
}
  • @Transactional is implemented via AOP: start transaction before, commit after, rollback on exception.

Example 2: Custom aspect

Java
@Aspect
@Component
public class LogAspect {
    @Around("execution(* com.example.service.*.*(..))")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        log.info("{} took {} ms", pjp.getSignature(), System.currentTimeMillis() - start);
        return result;
    }
}

Example 3: Advice types

TypeWhen it runs
@BeforeBefore method execution
@AfterAfter method (success or exception)
@AfterReturningAfter normal return
@AfterThrowingAfter exception thrown
@AroundWraps entire method; controls execution and return

Example 4: Pointcut expressions

Java
@Pointcut("execution(* com.example.service.*.*(..))")  // all methods in service package
@Pointcut("@annotation(com.example.Audited)")          // methods with @Audited
@Pointcut("@within(org.springframework.stereotype.Service)")  // methods in @Service classes

Core Mechanism / Behavior

  • Proxy: Created at runtime; intercepts calls to the target. Self-invocation (this.method()) does not go through the proxy.
  • Weaving: At runtime; Spring wraps beans with proxy beans. No bytecode modification at build time.
  • Order: Multiple aspects have order; use @Order to control.

Key Rules

  • Self-invocation in the same class is not intercepted; use proxy reference or self-injection to trigger the aspect.
  • Pointcut should be precise to avoid unintended interception; use @within, @annotation for annotation-based matching.
  • In @Around, must call proceed() or the original method will not run; preserve exception and return value propagation.

What's Next

See Transaction Management, Validation. See Reflection for dynamic proxy internals.