Spring Framework

Aspect-Oriented Programming with Spring AOP and AspectJ

Intermediate8 min readUpdated

Logging, timing, retries, security checks and transactions cut across every layer of an application. Spring AOP lets you write each once as an aspect and apply it declaratively. After this guide you can write aspects with @Aspect, target methods precisely with pointcut expressions, choose the right advice type, and — most importantly — explain why the proxy model means some calls are never intercepted.

What you will learn

  • Define aspect, join point, pointcut, advice and weaving and relate them to Spring's proxy model
  • Write @Around, @Before, @AfterReturning and @AfterThrowing advice with @Aspect
  • Compose pointcut expressions with execution, within, @annotation, args and bean designators
  • Explain the difference between JDK dynamic proxies and CGLIB subclass proxies and when each is used
  • Diagnose advice that silently does not run because of self-invocation, final methods or non-Spring instantiation

Some behaviour refuses to stay in one place. Timing a method, checking a permission, retrying on a transient failure, opening a transaction — each is needed in dozens of classes across every layer, and copy-pasting the same try/finally into each one scatters a single decision across the codebase. Aspect-oriented programming (AOP) names this problem — cross-cutting concerns — and offers a way to write the behaviour once and declare where it applies. Spring's @Transactional, @Cacheable, @Async, @PreAuthorize and @Retryable are all AOP underneath, so understanding the mechanism is the difference between using those annotations and debugging them. This guide targets Spring Framework 6.x.

Vocabulary

AOP has a small, precise vocabulary borrowed from AspectJ, and Spring uses it verbatim.

TermMeaningIn Spring AOP
Join pointA point in program execution where behaviour could be addedAlways the execution of a method on a Spring bean
PointcutA predicate selecting join pointsAn AspectJ expression such as execution(* com.shop.service.*.*(..))
AdviceThe behaviour to run at a join pointA method in an aspect annotated @Before, @Around, etc.
AspectA module bundling pointcuts and adviceA @Aspect-annotated bean
TargetThe object being advisedYour bean
ProxyThe object created to apply adviceA JDK or CGLIB proxy wrapping the target
WeavingLinking aspects to codeAt runtime, by creating proxies during bean post-processing

The restriction in the first row is the one that matters: Spring AOP only sees method executions on beans it created. Field accesses, constructors, static methods and objects you build with new are invisible to it.

Your first aspect

Enable the machinery with @EnableAspectJAutoProxy on a configuration class, add spring-aop and aspectjweaver to the classpath (the latter supplies the pointcut parser even though no AspectJ compilation happens), and declare an aspect as an ordinary bean:

@Aspect
@Component
public class TimingAspect {

    private static final Logger log = LoggerFactory.getLogger(TimingAspect.class);

    @Around("execution(public * com.example.shop.service..*(..))")
    public Object time(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.nanoTime();
        try {
            return pjp.proceed();                       // run the real method
        } finally {
            long micros = (System.nanoTime() - start) / 1_000;
            log.debug("{} took {} µs", pjp.getSignature().toShortString(), micros);
        }
    }
}

At startup the auto-proxy creator inspects every bean; if any pointcut in any aspect matches at least one of its methods, the bean is replaced in the container by a proxy. Every other bean that depends on it receives the proxy. When OrderService.confirm() is called on the proxy, the proxy runs the matching advice chain, and proceed() invokes the real method on the wrapped target.

Advice types

Five kinds of advice exist; choose the least powerful one that does the job.

  • @Before runs before the method. It cannot stop the call except by throwing.
  • @AfterReturning runs after a normal return and can read the return value with the returning attribute.
  • @AfterThrowing runs when the method throws and can bind the exception with throwing. It does not swallow the exception.
  • @After runs on both normal and exceptional exit, like finally.
  • @Around wraps the call. It receives a ProceedingJoinPoint, decides whether and how many times to call proceed(), can change arguments and return value, and can catch exceptions. It is the only advice that can implement retry, caching or transaction demarcation.
@Aspect
@Component
public class AuditAspect {

    @Before("@annotation(audited) && args(id, ..)")     // bind the annotation and first argument
    public void logIntent(JoinPoint jp, Audited audited, long id) {
        Audit.record(audited.value(), jp.getSignature().getName(), id);
    }

    @AfterThrowing(pointcut = "within(com.example.shop.payment..*)", throwing = "ex")
    public void alertOnPaymentFailure(PaymentException ex) {
        Alerts.raise("payment failure", ex);
    }

    @AfterReturning(pointcut = "execution(* com.example.shop.service.OrderService.place(..))",
                    returning = "order")
    public void indexOrder(Order order) {
        SearchIndex.add(order);
    }
}

@Around advice must return proceed()'s result (or a deliberate replacement) and declare throws Throwable. Forgetting the return turns every advised method into one that returns null — a bug that is startling to see and easy to make.

Pointcut expressions

Spring supports a subset of AspectJ's pointcut designators. The ones you will use:

DesignatorMatchesExample
execution(…)Method signature patternexecution(public * *..OrderService.*(..))
within(…)All methods of types in a package/classwithin(com.example.shop.service..*)
@within(…)Types carrying an annotation@within(org.springframework.stereotype.Service)
@annotation(…)Methods carrying an annotation@annotation(com.example.Audited)
args(…)Runtime argument typesargs(java.io.Serializable, ..)
bean(…)Spring bean name patternbean(*Repository)
this(…) / target(…)Proxy / target typetarget(com.example.Refundable)

The execution pattern reads modifiers? return-type declaring-type?.method-name(params) throws?. In it, * matches one token (any return type, any method name, a single parameter), .. in a parameter list matches any number of parameters, and .. in a package name matches sub-packages.

Reusable pointcuts are declared as empty methods annotated @Pointcut and combined with &&, || and !:

@Aspect
public class SystemArchitecture {

    @Pointcut("within(com.example.shop..web..*)")
    public void webLayer() {}

    @Pointcut("within(com.example.shop..service..*)")
    public void serviceLayer() {}

    @Pointcut("execution(* com.example.shop..repository.*.*(..))")
    public void dataAccessOperation() {}

    @Pointcut("serviceLayer() && @annotation(org.springframework.transaction.annotation.Transactional)")
    public void transactionalService() {}
}

Other aspects reference them by fully qualified name: @Around("com.example.shop.SystemArchitecture.serviceLayer()"). Centralising pointcuts in one class turns "which methods are advised" from an archaeology exercise into a single readable file.

Prefer annotation-based pointcuts (@annotation, @within) for behaviour that a developer should opt into explicitly, such as auditing or retries; prefer package-based pointcuts (within, execution) for architectural rules that apply to a whole layer.

Proxies: how the trick works

Spring creates one of two proxy kinds.

A JDK dynamic proxy is a class generated at runtime that implements the target's interfaces and forwards each call through an InvocationHandler. It can only be used where an interface exists, and it can only be injected by interface type: a field of type OrderServiceImpl cannot receive a JDK proxy of OrderService, and the container will fail with an "expected single matching bean" or BeanNotOfRequiredTypeException error.

A CGLIB proxy is a generated subclass of the target class that overrides its public and protected methods. It needs no interface, can be injected by concrete type, and is the default in Spring Boot. Its constraints are the constraints of subclassing: the class and the advised methods must not be final, and the proxy must be able to call a constructor — Spring 4+ uses Objenesis to skip constructor invocation, so a class without a no-arg constructor still works.

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)   // always CGLIB, as Boot does
public class AopConfig { }

Whichever kind is created, the proxy holds a reference to the real target and delegates after the advice chain runs. Three consequences follow, and they explain almost every "AOP is not working" question.

Self-invocation is not intercepted

@Service
public class InvoiceService {

    public void closeMonth() {
        for (var account : accounts()) {
            issue(account);            // this.issue(): direct call, proxy bypassed
        }
    }

    @Transactional
    public void issue(Account account) { … }   // NOT transactional when called from closeMonth
}

The this inside the target is the raw object, not the proxy. closeMonth calls issue on the raw object, so the transaction interceptor never sees it. The fix that keeps the design honest is to move issue into a separate bean. The workaround is to inject the bean's own proxy (ObjectProvider<InvoiceService> self) and call self.getObject().issue(account), which is legal but should be commented, because the next reader will not expect it.

Only Spring-created beans are proxied

An object created with new, or returned from a factory method that Spring does not manage, has no proxy and receives no advice. Prototype beans obtained from the container are proxied; the objects they create themselves are not.

The runtime type changes

service.getClass() returns the proxy class. instanceof OrderService still works for both proxy kinds when OrderService is an interface; for CGLIB, instanceof OrderServiceImpl also works because the proxy is a subclass. Use AopUtils.getTargetClass(bean) or AopProxyUtils.ultimateTargetClass in the rare framework-style code that needs the real class.

Ordering and multiple aspects

When several aspects match one join point, their order is undefined unless you specify it with @Order on the aspect classes (lower value runs first, i.e. outermost). Spring's own interceptors default to Ordered.LOWEST_PRECEDENCE too — the transaction interceptor's order is configurable on @EnableTransactionManagement — so a custom aspect with no @Order has no defined position relative to @Transactional. If your retry aspect must run outside the transaction so that each attempt gets a fresh one, give it a lower order value explicitly and leave the transaction interceptor at its default.

When Spring AOP is not enough: AspectJ weaving

Full AspectJ modifies bytecode instead of wrapping objects. It can advise constructors, field reads and writes, static and private methods, and classes Spring never instantiates. It comes in two flavours: compile-time weaving via the ajc compiler or a Maven/Gradle plugin, and load-time weaving via a Java agent (-javaagent:aspectjweaver.jar, or Spring's @EnableLoadTimeWeaving with a suitable server or instrumentation agent). Spring supports both and can inject dependencies into AspectJ-woven aspects and even into domain objects (@Configurable). The cost is a more involved build and stack traces that show synthetic methods. Most teams never need it; when they think they do, the real problem is usually self-invocation, and the better fix is a small refactoring.

Common mistakes

Forgetting return in @Around advice. Every advised method returns null. The compiler cannot catch it because the advice returns Object.

Advising a class injected by its concrete type with JDK proxies. Startup fails because the proxy only implements the interface. Set proxyTargetClass = true or inject by interface.

A pointcut that matches too much. execution(* *(..)) advises every bean including Spring's own internals and can create proxies of classes that must not be proxied. Always anchor to your package.

Expecting advice on a final class or method under CGLIB. The subclass cannot override it; Spring logs a warning at startup and the method runs unadvised.

Putting business logic in aspects. Aspects are for concerns that are genuinely orthogonal — timing, auditing, transactions. Validation rules and workflow decisions belong in the service, where they are visible and testable.

Testing an aspect by unit-testing the target. A plain new OrderService() has no proxy. Verify aspects with a Spring test context that loads the aspect and the target, or test the advice method directly with a mocked ProceedingJoinPoint.

Best practices

  • Keep aspects small, stateless and few. Two or three well-named aspects for logging, auditing and resilience are a healthy number; twenty are a maintenance problem.
  • Declare pointcuts once in a shared class and reference them.
  • Prefer annotation-driven pointcuts for opt-in behaviour so that reading a method reveals what wraps it.
  • Give every aspect an explicit @Order when more than one can apply to the same method.
  • Standardise on CGLIB proxies (proxyTargetClass = true) so injection by concrete type and by interface both work, and avoid final on Spring beans.
  • Use Spring's built-in aspects (@Transactional, @Cacheable, @Async, @Retryable from Spring Retry) before writing your own for the same concern.

Key takeaways

  • AOP separates cross-cutting behaviour into aspects; Spring implements it with runtime proxies around beans, limited to method execution.
  • @Aspect beans hold pointcuts and advice; @Around is the most powerful advice and the only one that can replace or repeat the call.
  • Pointcut expressions combine execution, within, @annotation, args and bean designators; centralise them in one class.
  • JDK proxies implement interfaces; CGLIB proxies subclass the target and are the Spring Boot default. Neither can advise final or static methods.
  • Calls a bean makes to its own methods bypass the proxy and receive no advice — the single most common AOP bug, affecting @Transactional and @Cacheable alike.
  • Full AspectJ weaving removes those limits at the cost of build complexity; it is rarely necessary.

Sources and further reading

Frequently asked questions

Why is my aspect not applied when one method calls another in the same class?
Spring AOP works by wrapping the bean in a proxy. Only calls that arrive through the proxy are advised. When a method calls this.otherMethod(), the call goes directly to the target object and skips the proxy, so no advice runs. Move the advised method to a separate bean, inject the bean's own proxy via ObjectProvider, or switch to AspectJ compile-time or load-time weaving if you truly need self-invocation advised.
Can Spring AOP advise private, static or final methods?
No. A JDK proxy can only implement interface methods; a CGLIB proxy overrides methods in a generated subclass, which excludes final methods and final classes, and static or private methods are not virtual at all. Full AspectJ weaving modifies bytecode directly and can advise any of them, at the cost of a build or agent setup.
Does Spring use JDK proxies or CGLIB by default?
The Spring Framework's @EnableAspectJAutoProxy defaults to JDK dynamic proxies when the bean implements at least one interface, and CGLIB otherwise. Spring Boot flips the default to CGLIB (proxyTargetClass=true) so that beans can be injected by their concrete class. Either way you can force class-based proxies with proxyTargetClass = true.
Is Spring AOP the same as AspectJ?
No. Spring AOP reuses AspectJ's annotations and pointcut language but implements them with runtime proxies limited to method execution on Spring beans. AspectJ is a full language extension with a compiler and weaver that can advise field access, constructors, static methods and objects Spring never sees. Spring AOP covers the vast majority of enterprise needs; reach for AspectJ only when the proxy model is genuinely insufficient.