Spring AOP: how aspects work and where they stop working

Spring AOP lets you run code before, after or around method calls without touching those methods, which is how @Transactional, @Cacheable and @PreAuthorize work. It does this with proxies, and every limit of Spring AOP is a limit of the proxy. This page builds a proxy by hand, then runs each advice type, the main pointcut expressions, aspect ordering and the traps.

Contents

What AOP is and how Spring implements it

Some code belongs to many methods at once: logging, timing, retries, security checks, transactions. Written inline, it repeats in every method and hides the business logic. Aspect-oriented programming (AOP) moves it into one place, an aspect, and describes where it applies with an expression instead of copying it into each method.

AOP has its own vocabulary, and the terms map onto plain Java concepts:

  • Join point: a point in the running program where extra code can run. In Spring AOP this is always the execution of a method on a Spring bean.
  • Pointcut: an expression that selects join points, such as "every public method of a class whose name ends in Service".
  • Advice: the code that runs at the selected join points, and when it runs: before the method, after it, or around it.
  • Aspect: a class that groups pointcuts and advice, marked with @Aspect.
  • Target and proxy: the target is your bean; the proxy is the object Spring creates around it and injects in its place, which runs the advice and then calls the target.

Spring does not change your class files. When the context starts, a bean post-processor checks every bean against every pointcut. If any pointcut matches, it replaces the bean with a proxy. A call on the proxy walks a chain of interceptors, one per matching advice, and the last link calls the real method. This is why Spring AOP works only for calls that go through the proxy, and only on beans Spring created.

Spring builds one of two kinds of proxy:

The two kinds of Spring proxy
ProxyHow it is madeWhen it is usedLimits
JDK dynamic proxyjava.lang.reflect.Proxy implements the bean's interfacesPlain Spring, when the bean implements at least one interfaceOnly interface methods are advised; the bean cannot be injected as its class
CGLIB proxyA subclass generated at startup that overrides the methodsClasses without interfaces, and always in Spring Boot (spring.aop.proxy-target-class=true)Cannot override final or private methods, or subclass a final class

Spring AOP is one way to apply aspects. AspectJ, the language that the @Aspect annotations come from, can weave advice into the bytecode itself:

Spring AOP compared with AspectJ weaving
FeatureSpring AOPAspectJ weaving
MechanismRuntime proxy around a beanAdvice woven into class files, at compile time or class-load time
Join pointsMethod execution on Spring beansMethod calls and executions, constructors, field access, static initialisers
Calls on thisNot advisedAdvised
Objects created with newNot advisedAdvised
Build changesNoneThe AspectJ compiler or a -javaagent

Spring uses only AspectJ's annotations and its pointcut parser, from the aspectjweaver jar; the proxy is still Spring's own. In Spring Boot 4 the jar comes with spring-boot-starter-aspectj, which was called spring-boot-starter-aop in Spring Boot 3.x. Spring Boot switches on @Aspect support by itself when the jar is present. The examples on this page run on Spring Framework 7.0 with aspectjweaver 1.9.25 and no Spring Boot, so they add @EnableAspectJAutoProxy themselves.

A proxy built by hand

Before any annotations, it helps to see the machinery. ProxyFactory is the class Spring itself uses to build proxies; this program wraps the same target twice, once with each kind of proxy, and adds one interceptor that logs the call:

Java
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;

public class ProxyByHand {

    interface PriceService {
        int price(String item);
    }

    static class SimplePriceService implements PriceService {
        @Override
        public int price(String item) {
            System.out.println("    target computes the price of " + item);
            return item.length() * 10;
        }
    }

    public static void main(String[] args) {
        MethodInterceptor logging = invocation -> {
            System.out.println("  before " + invocation.getMethod().getName()
                    + Arrays.toString(invocation.getArguments()));
            Object result = invocation.proceed();       // calls the next interceptor or the target
            System.out.println("  after, returned " + result);
            return result;
        };

        ProxyFactory jdk = new ProxyFactory(new SimplePriceService());
        jdk.addInterface(PriceService.class);
        jdk.addAdvice(logging);
        PriceService viaInterface = (PriceService) jdk.getProxy();

        ProxyFactory cglib = new ProxyFactory(new SimplePriceService());
        cglib.setProxyTargetClass(true);
        cglib.addAdvice(logging);
        SimplePriceService viaSubclass = (SimplePriceService) cglib.getProxy();

        System.out.println("Interface-based proxy:");
        System.out.println("  class      : " + viaInterface.getClass().getName());
        System.out.println("  JDK proxy  : " + AopUtils.isJdkDynamicProxy(viaInterface));
        System.out.println("  is a SimplePriceService: "
                + (viaInterface instanceof SimplePriceService));
        viaInterface.price("book");

        System.out.println("Class-based proxy:");
        System.out.println("  class      : " + viaSubclass.getClass().getName());
        System.out.println("  CGLIB proxy: " + AopUtils.isCglibProxy(viaSubclass));
        System.out.println("  superclass : " + viaSubclass.getClass().getSuperclass().getName());
        viaSubclass.price("pen");
    }
}
Output
Interface-based proxy:
  class      : $Proxy0
  JDK proxy  : true
  is a SimplePriceService: false
  before price[book]
    target computes the price of book
  after, returned 40
Class-based proxy:
  class      : ProxyByHand$SimplePriceService$$SpringCGLIB$$0
  CGLIB proxy: true
  superclass : ProxyByHand$SimplePriceService
  before price[pen]
    target computes the price of pen
  after, returned 30
  • The first proxy's class is $Proxy0, generated by the JDK. It implements PriceService but is not a SimplePriceService, so code that asks for the class instead of the interface cannot use it.
  • The second proxy's class is ProxyByHand$SimplePriceService$$SpringCGLIB$$0, and its superclass is the target's class. It passes an instanceof SimplePriceService check, which is why Spring Boot prefers it.
  • In both cases the interceptor printed before, then the target ran, then the interceptor printed the result, 40 for book and 30 for pen. invocation.proceed() is the call that moves on to the target; an interceptor that does not call it stops the method from running at all.

The MethodInterceptor interface comes from AOP Alliance, a small API that Spring includes. Every @Aspect advice is turned into one of these interceptors, and so are @Transactional, @Cacheable and @Async. The Java dynamic proxy page shows how java.lang.reflect.Proxy works without Spring.

@Around advice: a retry aspect

Around advice is the most powerful type: it decides whether the method runs, how many times, with which arguments, and what the caller receives. A retry is a good test because it must call the method more than once. The client below fails twice before it succeeds, and a second method always fails:

Java
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

public class AroundAdvice {

    @Aspect
    static class RetryAspect {
        @Around("execution(* AroundAdvice.InventoryClient.*(..))")
        public Object retry(ProceedingJoinPoint call) throws Throwable {
            String name = call.getSignature().toShortString();
            for (int attempt = 1; ; attempt++) {
                try {
                    System.out.println("  " + name + " " + Arrays.toString(call.getArgs())
                            + ", attempt " + attempt);
                    return call.proceed();
                } catch (IllegalStateException e) {
                    System.out.println("    failed: " + e.getMessage());
                    if (attempt == 3) {
                        throw e;
                    }
                }
            }
        }
    }

    static class InventoryClient {
        private int calls;

        public int stockOf(String item) {
            calls++;
            if (calls < 3) {
                throw new IllegalStateException("inventory service timed out");
            }
            return 7;
        }

        public int reserve(String item) {
            throw new IllegalStateException("inventory service is down");
        }
    }

    @Configuration
    @EnableAspectJAutoProxy
    static class Config {
        @Bean
        RetryAspect retryAspect() {
            return new RetryAspect();
        }

        @Bean
        InventoryClient inventoryClient() {
            return new InventoryClient();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            InventoryClient client = context.getBean(InventoryClient.class);
            System.out.println("Bean class: " + client.getClass().getSimpleName());
            System.out.println("stockOf:");
            System.out.println("  result: " + client.stockOf("book"));
            System.out.println("reserve:");
            try {
                client.reserve("book");
            } catch (IllegalStateException e) {
                System.out.println("  caller sees: " + e.getMessage());
            }
        }
    }
}
Output
Bean class: AroundAdvice$InventoryClient$$SpringCGLIB$$0
stockOf:
  InventoryClient.stockOf(..) [book], attempt 1
    failed: inventory service timed out
  InventoryClient.stockOf(..) [book], attempt 2
    failed: inventory service timed out
  InventoryClient.stockOf(..) [book], attempt 3
  result: 7
reserve:
  InventoryClient.reserve(..) [book], attempt 1
    failed: inventory service is down
  InventoryClient.reserve(..) [book], attempt 2
    failed: inventory service is down
  InventoryClient.reserve(..) [book], attempt 3
    failed: inventory service is down
  caller sees: inventory service is down
  • The bean is InventoryClient$$SpringCGLIB$$0: the pointcut matched, so the context replaced the bean with a CGLIB proxy. The class has no interface, so Spring had to use CGLIB.
  • stockOf failed on attempts 1 and 2, and the aspect caught each IllegalStateException and called proceed() again. Attempt 3 returned 7, and the caller never knew about the failures.
  • reserve failed three times, so the aspect rethrew the third exception, and the caller saw inventory service is down.
  • call.getSignature().toShortString() printed InventoryClient.stockOf(..), and call.getArgs() gave the argument book. These are the usual way to log which method an aspect is handling.

An @Around method must return what the method returns (here an int, boxed into an Object) and must declare throws Throwable, because proceed() can throw anything the target throws. Forgetting to return the result of proceed() is a common bug: the caller then receives null, or a NullPointerException for a primitive return type. For production retries, Spring Framework 7.0 also has @Retryable in the core framework, which is built on the same kind of interceptor.

The five advice types and the order they run in

Each advice type runs at a different moment. This program puts all five on one method and calls it once with an amount that succeeds and once with one that fails, so every type shows when it fires:

Java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

public class AdviceOrder {

    @Aspect
    static class TracingAspect {
        @Pointcut("execution(public * AdviceOrder.PaymentService.*(..))")
        void payments() {
        }

        @Around("payments()")
        public Object around(ProceedingJoinPoint call) throws Throwable {
            System.out.println("  @Around, before proceed()");
            try {
                Object result = call.proceed();
                System.out.println("  @Around, after proceed() returned " + result);
                return result;
            } catch (RuntimeException e) {
                System.out.println("  @Around, proceed() threw " + e.getMessage());
                throw e;
            }
        }

        @Before("payments()")
        public void before(JoinPoint jp) {
            System.out.println("  @Before " + jp.getSignature().getName());
        }

        @AfterReturning(pointcut = "payments()", returning = "result")
        public void afterReturning(Object result) {
            System.out.println("  @AfterReturning, result = " + result);
        }

        @AfterThrowing(pointcut = "payments()", throwing = "error")
        public void afterThrowing(RuntimeException error) {
            System.out.println("  @AfterThrowing, error = " + error.getMessage());
        }

        @After("payments()")
        public void after() {
            System.out.println("  @After (runs either way, like finally)");
        }
    }

    static class PaymentService {
        public String pay(int amount) {
            System.out.println("    target: pay(" + amount + ")");
            if (amount > 100) {
                throw new IllegalArgumentException("limit exceeded");
            }
            return "receipt-" + amount;
        }
    }

    @Configuration
    @EnableAspectJAutoProxy
    static class Config {
        @Bean
        TracingAspect tracingAspect() {
            return new TracingAspect();
        }

        @Bean
        PaymentService paymentService() {
            return new PaymentService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            PaymentService service = context.getBean(PaymentService.class);
            System.out.println("pay(40), success:");
            service.pay(40);
            System.out.println("pay(500), failure:");
            try {
                service.pay(500);
            } catch (IllegalArgumentException e) {
                System.out.println("  caller sees: " + e.getMessage());
            }
        }
    }
}
Output
pay(40), success:
  @Around, before proceed()
  @Before pay
    target: pay(40)
  @AfterReturning, result = receipt-40
  @After (runs either way, like finally)
  @Around, after proceed() returned receipt-40
pay(500), failure:
  @Around, before proceed()
  @Before pay
    target: pay(500)
  @AfterThrowing, error = limit exceeded
  @After (runs either way, like finally)
  @Around, proceed() threw limit exceeded
  caller sees: limit exceeded
  • On success, the order was @Around (before proceed()), @Before, the target, @AfterReturning with the result receipt-40, @After, and finally the rest of @Around.
  • On failure, @AfterReturning did not run. @AfterThrowing ran instead, with the exception limit exceeded, then @After, and then the catch block in @Around. The exception still reached the caller, because @AfterThrowing only observes it.
  • @After ran in both cases, like a finally block.
Advice types
AnnotationRunsCan change the outcomeTypical use
@BeforeBefore the methodOnly by throwing, which stops the callArgument checks, audit of attempts
@AfterReturningAfter a normal returnNo; it sees the result but cannot replace itLogging results, metrics for successful calls
@AfterThrowingAfter the method throwsOnly by throwing a different exceptionError logging, exception translation
@AfterAfter either outcomeNoReleasing resources, clearing context
@AroundAround the callYes: skip the call, retry it, change arguments or the resultTiming, retries, caching, transactions

The @Pointcut method payments() names the expression once, so the five advice methods refer to it by name instead of repeating it. Within one aspect, Spring orders advice by type since Spring Framework 5.2.7: @Around, @Before, @After, @AfterReturning, @AfterThrowing, from highest to lowest precedence. Higher precedence means earlier on the way in and later on the way out, so @After, which outranks @AfterReturning, ran after it, as the output shows. Two advice methods of the same type in the same aspect have no defined order; put them in separate aspects with @Order when the order matters.

Use the least powerful type that does the job. @Before and @AfterReturning cannot forget to call proceed() or lose the return value, so they are harder to get wrong than @Around.

Pointcut expressions

The pointcut decides which methods an aspect touches, so it is where most aspect bugs start: too broad, and the advice runs on methods it should not; too narrow, and it silently does nothing. This program has one aspect with four common designators and prints which of them match each call:

Java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

public class PointcutKinds {

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface Audited {
        String action();
    }

    @Aspect
    static class Matchers {
        @Before("execution(* PointcutKinds.AccountService.find*(..))")
        public void byName(JoinPoint jp) {
            System.out.println("  execution(* find*(..))     matched " + name(jp));
        }

        @Before("within(PointcutKinds.AccountService) && args(id)")
        public void byArgs(JoinPoint jp, long id) {
            System.out.println("  args(id), a long           matched " + name(jp) + ", id = " + id);
        }

        @Before("@annotation(audited)")
        public void byAnnotation(JoinPoint jp, Audited audited) {
            System.out.println("  @annotation(Audited)       matched " + name(jp)
                    + ", action = " + audited.action());
        }

        @Before("bean(report*)")
        public void byBeanName(JoinPoint jp) {
            System.out.println("  bean(report*)              matched " + name(jp));
        }

        private static String name(JoinPoint jp) {
            return jp.getSignature().getDeclaringType().getSimpleName()
                    + "." + jp.getSignature().getName();
        }
    }

    static class AccountService {
        public String findById(long id) {
            return "account " + id;
        }

        public String findByOwner(String owner) {
            return "account of " + owner;
        }

        @Audited(action = "CLOSE")
        public void close(long id) {
        }
    }

    static class ReportService {
        public void monthly() {
        }
    }

    @Configuration
    @EnableAspectJAutoProxy
    static class Config {
        @Bean
        Matchers matchers() {
            return new Matchers();
        }

        @Bean
        AccountService accountService() {
            return new AccountService();
        }

        @Bean
        ReportService reportService() {
            return new ReportService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            AccountService accounts = context.getBean(AccountService.class);
            System.out.println("findById(42):");
            accounts.findById(42);
            System.out.println("findByOwner(\"ann\"):");
            accounts.findByOwner("ann");
            System.out.println("close(42):");
            accounts.close(42);
            System.out.println("reportService.monthly():");
            context.getBean(ReportService.class).monthly();
        }
    }
}
Output
findById(42):
  args(id), a long           matched AccountService.findById, id = 42
  execution(* find*(..))     matched AccountService.findById
findByOwner("ann"):
  execution(* find*(..))     matched AccountService.findByOwner
close(42):
  @annotation(Audited)       matched AccountService.close, action = CLOSE
  args(id), a long           matched AccountService.close, id = 42
reportService.monthly():
  bean(report*)              matched ReportService.monthly
  • findById(42) matched two advice methods: the name pattern find*, and args(id), which matches a method with exactly one long parameter and passes its value, 42, to the advice.
  • findByOwner("ann") matched only the name pattern. Its argument is a String, so args(id) with a long id parameter does not match.
  • close(42) matched @annotation(audited), which bound the annotation itself, so the advice read action = CLOSE. It also matched args(id).
  • bean(report*) matched the bean named reportService. This designator is specific to Spring and selects by bean name, not by type.
Pointcut designators supported by Spring AOP
DesignatorMatchesExample
executionMethod signature: modifiers, return type, class, name, parametersexecution(public * com.shop..*Service.*(..))
withinEvery method of matching types or packageswithin(com.shop.order..*)
@annotationMethods that carry an annotation@annotation(com.shop.Audited)
@withinMethods of classes that carry an annotation@within(org.springframework.stereotype.Service)
argsRuntime argument types; can bind valuesargs(id, ..)
this, targetThe proxy's type, or the target's typetarget(com.shop.Repository)
beanSpring bean names, with * wildcardsbean(*Service)

In execution, * matches one element (any return type, any name) and .. matches any number of parameters, or any number of package levels in a type pattern. Expressions combine with &&, || and !. Two habits keep pointcuts safe. First, prefer a custom annotation with @annotation: the methods that are advised are then visible in the code, and renaming a method cannot silently move it out of the pointcut. Second, never write a pointcut that matches every bean, such as execution(* *(..)): it wraps beans from Spring and from libraries too, which slows every call and fails on beans whose classes are final.

Ordering several aspects

When two aspects match the same method, their order matters: a security check should run before the timing starts, and a transaction should be open before a retry repeats work inside it. Here a security aspect and a metrics aspect both wrap one method, and the metrics bean is even registered first:

Java
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;

public class AspectOrdering {

    static Object wrap(String name, ProceedingJoinPoint call) throws Throwable {
        System.out.println("  enter " + name);
        try {
            return call.proceed();
        } finally {
            System.out.println("  leave " + name);
        }
    }

    @Aspect
    @Order(1)
    static class SecurityAspect {
        @Around("execution(* AspectOrdering.TransferService.*(..))")
        public Object check(ProceedingJoinPoint call) throws Throwable {
            return wrap("security (order 1)", call);
        }
    }

    @Aspect
    @Order(2)
    static class MetricsAspect {
        @Around("execution(* AspectOrdering.TransferService.*(..))")
        public Object time(ProceedingJoinPoint call) throws Throwable {
            return wrap("metrics  (order 2)", call);
        }
    }

    static class TransferService {
        public void transfer() {
            System.out.println("    target: transfer()");
        }
    }

    @Configuration
    @EnableAspectJAutoProxy
    static class Config {
        @Bean
        MetricsAspect metricsAspect() {
            return new MetricsAspect();
        }

        @Bean
        SecurityAspect securityAspect() {
            return new SecurityAspect();
        }

        @Bean
        TransferService transferService() {
            return new TransferService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            context.getBean(TransferService.class).transfer();
        }
    }
}
Output
enter security (order 1)
  enter metrics  (order 2)
    target: transfer()
  leave metrics  (order 2)
  leave security (order 1)
  • The aspect with the lower @Order value, security with 1, is the outer layer: it was entered first and left last.
  • Metrics, with 2, wrapped the target more tightly, so its timing would not include the security check.
  • The registration order of the beans did not matter. Without @Order, the order of two aspects is undefined, and it can change when an unrelated bean is added.

Spring's own interceptors take part in the same ordering. @EnableTransactionManagement has an order attribute that defaults to the lowest precedence, so a custom aspect without @Order may end up inside or outside the transaction. If an aspect must run inside the transaction, for example to retry only the statement and not the whole unit of work, give both an explicit order. @Order works on the aspect class; it has no effect on single advice methods.

Calls the proxy never sees

Every limit of Spring AOP follows from one fact: the advice lives in the proxy, so only calls that pass through the proxy are advised. This program uses interface-based proxies (proxyTargetClass = false, the default in plain Spring) to show four cases:

Java
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

public class ProxyTraps {

    @Aspect
    static class CallLogger {
        @Before("within(ProxyTraps.*Service)")
        public void log(JoinPoint jp) {
            System.out.println("    [advice] " + jp.getSignature().getName());
        }
    }

    interface Notifier {
        void notifyUser(String user);
    }

    static class EmailService implements Notifier {
        @Override
        public void notifyUser(String user) {
            System.out.println("    notifyUser(" + user + ")");
        }
    }

    static class ReportService {
        public void build() {
            System.out.println("    build()");
            this.render();                                        // skips the proxy
            ((ReportService) AopContext.currentProxy()).render(); // goes through it
        }

        public void render() {
            System.out.println("    render()");
        }

        public final void export() {
            System.out.println("    export() (final)");
        }
    }

    @Configuration
    @EnableAspectJAutoProxy(proxyTargetClass = false, exposeProxy = true)
    static class Config {
        @Bean
        CallLogger callLogger() {
            return new CallLogger();
        }

        @Bean
        EmailService emailService() {
            return new EmailService();
        }

        @Bean
        ReportService reportService() {
            return new ReportService();
        }
    }

    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(Config.class)) {
            System.out.println("1. Self-invocation:");
            context.getBean(ReportService.class).build();

            System.out.println("2. Final method:");
            context.getBean(ReportService.class).export();

            System.out.println("3. Interface proxy, looked up by its class:");
            try {
                context.getBean(EmailService.class);
            } catch (NoSuchBeanDefinitionException e) {
                System.out.println("    " + e.getClass().getSimpleName());
                Object bean = context.getBean("emailService");
                System.out.println("    JDK proxy: " + AopUtils.isJdkDynamicProxy(bean)
                        + ", is an EmailService: " + (bean instanceof EmailService));
            }
            System.out.println("4. Same bean, looked up by its interface:");
            context.getBean(Notifier.class).notifyUser("ann");
        }
    }
}
Output
1. Self-invocation:
    [advice] build
    build()
    render()
    [advice] render
    render()
2. Final method:
    export() (final)
3. Interface proxy, looked up by its class:
    NoSuchBeanDefinitionException
    JDK proxy: true, is an EmailService: false
4. Same bean, looked up by its interface:
    [advice] notifyUser
    notifyUser(ann)
Nov 14, 2026 9:32:40 PM org.springframework.aop.framework.CglibAopProxy doValidateClass
WARNING: Public final method [public final void ProxyTraps$ReportService.export()] cannot get proxied via CGLIB, consider removing the final marker or using interface-based JDK proxies.
  • Self-invocation: build() was advised, but its call this.render() printed render() with no [advice] line, because this is the target, not the proxy. The second call, through AopContext.currentProxy(), was advised. That works only with exposeProxy = true, and it ties the class to Spring AOP, so moving the method to another bean is usually the better fix.
  • Final method: export() ran with no advice. CGLIB cannot override a final method, so the call went straight to the target. Spring logged the warning at the end of the output when the context started; it appears last because it goes to standard error, and its first line, the date and time, differs on every run.
  • Interface proxy looked up by class: EmailService implements Notifier, so Spring made a JDK proxy. That proxy is not an EmailService, so getBean(EmailService.class) failed with NoSuchBeanDefinitionException. The same would happen with @Autowired EmailService. Spring Boot avoids this by using CGLIB proxies by default.
  • Lookup by interface: through Notifier, the same bean worked and was advised.

Three more cases are not shown, because nothing happens at all: private methods are never advised, objects created with new are not beans and get no proxy, and an aspect class is never itself advised by another aspect. The @Transactional page shows the same self-invocation and final-method traps with transactions, where the missing advice means data is committed that should have been rolled back.

Where Spring uses AOP for you

Many Spring annotations are aspects that ship with the framework. Knowing that they are proxies explains why they all share the traps above:

Spring features built on AOP proxies
AnnotationAdvice it addsEnabled by
@TransactionalBegin, commit or roll back around the method@EnableTransactionManagement, automatic in Spring Boot
@Cacheable, @CacheEvictReturn a cached value or skip the method@EnableCaching
@AsyncRun the method on another thread@EnableAsync
@PreAuthorize, @PostAuthorizeCheck permissions before or after the call@EnableMethodSecurity
@Validated with constraints on parametersValidate arguments and return valuesMethodValidationPostProcessor, automatic in Spring Boot
@RetryableCall the method again after a failure@EnableResilientMethods (Spring Framework 7.0)

None of these need aspectjweaver: they use Spring's own advisors, so they work in a project without the aspectj starter. The jar is needed only for your own @Aspect classes. See Spring caching, method security and validation for those features.

Choosing an approach

Ways to add behaviour around method calls
NeedApproach
Logging, timing or auditing across many beans@Aspect with @Around or @Before, selected by a custom annotation
Transactions, caching, async, security, validationThe Spring annotation for it, not a hand-written aspect
Behaviour around HTTP requests onlyA servlet filter or a HandlerInterceptor, which see the request and response
Wrapping one object, or code outside SpringProxyFactory, or a plain decorator class
Advice on private methods, constructors, field access or calls on thisAspectJ compile-time or load-time weaving
Two aspects on the same method@Order on each aspect class

An aspect is code that runs where nobody calls it, so keep each one small and its pointcut easy to read. When behaviour belongs to a single class, an ordinary method call is clearer than any aspect.