Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 119 ยท Spring Framework

Aspect-Oriented Programming

Learn Spring AOP - cross-cutting concerns, aspects, advice and pointcuts, @Around timing, how proxies work (built with java.lang.reflect.Proxy) and the self-invocation trap.

Some code doesn't belong to any one feature. Logging how long a method took, checking that the user may call it, starting and committing a transaction, retrying on a timeout, recording metrics: you need these in dozens of places, and each time the code is nearly identical. Written by hand, it buries the business logic under boilerplate and is easy to forget in the one method where it mattered. These are cross-cutting concerns, and aspect-oriented programming (AOP) is the technique for writing them once and applying them wherever they are needed.

You use Spring AOP every day even if you never write an aspect: @Transactional, @Cacheable, @Async, @PreAuthorize and @Retryable are all implemented with it. This lesson explains the vocabulary, shows Spring's @Aspect syntax, and then builds the machinery yourself with java.lang.reflect.Proxy. Once you have built a transactional proxy by hand, the famous "my @Transactional is ignored" bug will make complete sense. You should know how beans are created from Beans, Configuration and Component Scanning.

The problem: tangled and scattered code

Suppose you want to log the duration of every service call. Without AOP, the cleanest option is the decorator pattern: a wrapper class that implements the same interface, does the extra work and delegates to the real object.

Java Timing with a hand-written decorator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The business class stays clean, which is good. But the decorator only works for PriceService. An OrderService with five methods needs its own decorator with five copies of the same timing code, and so does every other service. Adding transactions, security and metrics multiplies the work again. AOP removes that duplication: you write the timing code once and declare where it applies. (The time printed varies from run to run.)

AOP vocabulary

Term Meaning In the example above
Aspect A module that implements a cross-cutting concern "timing"
Join point A point in the program where an aspect can run. In Spring AOP it is always a method execution the call to priceInCents
Advice The code that runs at a join point, and when: before, after, or around the nanoTime measurement
Pointcut An expression that selects join points "every method of every service"
Target The object whose method is advised CatalogPriceService
Proxy The object that callers actually talk to; it runs the advice and calls the target TimedPriceService
Weaving Linking aspects to targets Spring does it at runtime by creating proxies

Spring supports five kinds of advice:

  • @Before: runs before the method; can stop it only by throwing.
  • @AfterReturning: runs after a normal return and can see the return value.
  • @AfterThrowing: runs when the method throws and can see the exception.
  • @After: runs either way, like finally.
  • @Around: wraps the call completely. It decides whether, when and how often to call the target, can change arguments and return values, and can catch exceptions. It is the most powerful kind and the one used for timing, transactions, caching and retries.

Writing an aspect in Spring

In a Spring Boot application, add the AspectJ starter (spring-boot-starter-aspectj in Boot 4, called spring-boot-starter-aop in Boot 3) and write an aspect as a bean annotated with @Aspect:

Java
package com.example.shop.monitoring;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TimingAspect {

    @Pointcut("execution(public * com.example.shop.service..*(..))")
    void serviceMethods() {}

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

    @AfterThrowing(pointcut = "serviceMethods()", throwing = "error")
    public void logFailure(JoinPoint call, Exception error) {
        log.warn("{} failed: {}", call.getSignature().toShortString(), error.getMessage());
    }

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

Calling priceService.priceInCents("tent") now logs a line like CatalogPriceService.priceInCents(..) took 3 ms, and no service class mentions timing at all. The annotations come from AspectJ, the original Java AOP project; Spring uses AspectJ's annotation style and pointcut language but implements the weaving itself, with proxies.

Pointcut expressions

Pointcuts use AspectJ's expression language. The most common designators:

Expression Matches
execution(* com.example.shop.service.*.*(..)) any method of any class directly in the service package
execution(* com.example.shop..*Service.*(..)) methods of classes whose name ends in Service, in shop or any subpackage
execution(public String find*(Long)) public methods returning String, named find..., taking one Long
within(com.example.shop.web..*) every method of every type in web and its subpackages
@annotation(com.example.shop.Timed) methods annotated with @Timed
@within(org.springframework.stereotype.Service) methods of classes annotated with @Service
bean(*Repository) methods of beans whose name ends in Repository (Spring-only)
args(String, ..) methods whose first argument is a String

In execution(...), the parts are return type, declaring type and method name, and parameters; * matches one element and .. matches any number of packages or parameters. Pointcuts combine with &&, || and !.

Matching by annotation is usually the clearest choice: @annotation(com.example.shop.Timed) applies only where someone wrote @Timed, so the behavior is visible right in the code. Package-wide pointcuts are powerful but invisible; a developer reading the service has no idea it is being timed.

How Spring applies aspects: proxies

When Spring creates a bean, a BeanPostProcessor checks whether any pointcut matches one of its methods. If so, other beans don't receive the bean itself but a proxy wrapped around it (this happens in the "after initialization" step of the bean lifecycle). Every call on the proxy runs the matching advice and then the real method.

Spring creates proxies in two ways:

  • JDK dynamic proxies (java.lang.reflect.Proxy): a generated class that implements the bean's interfaces. Only works if the bean implements an interface, and the proxy can be injected only as that interface.
  • CGLIB proxies: a generated subclass of the bean's class that overrides its methods. Works without interfaces. Spring Boot uses CGLIB by default (spring.aop.proxy-target-class=true), so injecting by the concrete class also works.

JDK proxies are part of the standard library, so you can build one right now. Proxy.newProxyInstance creates an object implementing any interfaces you list and routes every call to an InvocationHandler. One handler can time every interface:

Java A timing proxy for any interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The same 15-line handler timed two unrelated interfaces, and it would time a hundred. Look at the last lines too. The proxy is an instance of a generated class (here $Proxy0; for public interfaces the JDK puts it in a package such as jdk.proxy1) that implements PriceService but is not a CatalogPriceService. That is why, with JDK proxies, injecting a bean by its concrete class fails in Spring with BeanNotOfRequiredTypeException, and why Spring Boot defaults to CGLIB subclasses. Test Doubles and Mockito uses the same Proxy API to build mocks.

Annotation-driven advice and advice order

Real applications usually combine several aspects on one method, and select them by annotation. Spring then builds an interceptor chain: each advice wraps the next one, and the innermost calls the target. @Order on the aspect class decides the nesting; the lowest value is the outermost.

The model below works the same way. Each Advice decides whether it matches a method (here: whether the method has a certain annotation), and Invocation.proceed() moves to the next advice in the chain, exactly like ProceedingJoinPoint.proceed().

Java An interceptor chain selected by annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The logging advice is the outer layer and timing the inner one, so the timing line appears between the log lines, and the time excludes the logging. The unannotated stock() passed straight through, and the exception from restock() reached the caller unchanged after the logging advice saw it. Spring's TransactionInterceptor, CacheInterceptor and security interceptors are links in exactly this kind of chain. When the order matters (for example, a retry advice must sit outside the transaction so each attempt gets a fresh transaction), set it with @Order on the aspects.

The self-invocation trap

Here is the most important consequence of proxy-based AOP. Advice runs only when a call goes through the proxy. A call from one method of the bean to another method of the same bean uses this, the raw target object, and bypasses the proxy completely:

Java
@Service
public class PayrollService {

    public void payAll(List<Payment> payments) {
        for (Payment p : payments) {
            transfer(p);                 // this.transfer(...): NOT through the proxy
        }
    }

    @Transactional
    public void transfer(Payment p) { ... }   // the annotation is ignored for the call above
}

The model below wraps an H2-backed account service in a transactional proxy, built just like Spring's: it opens a transaction for methods annotated with @Transactional, commits on success and rolls back on an exception. Watch what happens when a non-transactional method calls a transactional one on this.

Java A transactional proxy and the self-invocation trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first call went through the proxy: the failed transfer was rolled back and the total stayed 700. In the second call, only payAll went through the proxy, and it isn't transactional. Its internal this.transfer(...) calls hit the raw object, so no transaction was ever started, the withdrawal of 70 was committed on its own, and the total dropped to 630. No error message warns you about this; the annotation is simply not consulted.

The fixes, from best to worst:

  • Move the advised method to another bean. A separate TransferService injected into PayrollService means every call crosses a proxy. This is almost always the cleanest design.
  • Put the annotation on the outer method if the whole operation should be one transaction (@Transactional on payAll).
  • Call through the proxy explicitly: inject the bean into itself (@Lazy PayrollService self), or use TransactionTemplate for programmatic transactions. Both work but are easy to misuse.
  • Switch to AspectJ weaving, which modifies the bytecode itself, so even this calls are advised.

Other limitations of Spring AOP

Because Spring AOP is built on proxies, it inherits their rules:

  • Only Spring beans are advised. An object you create with new has no proxy around it.
  • Only method executions. No field access, no constructor calls.
  • Not private, final or static methods. A CGLIB subclass can't override them, and a JDK proxy only sees interface methods. Such methods run without advice, silently.
  • Not final classes, when CGLIB is needed (for example, Kotlin classes, which are final by default; the kotlin-spring compiler plugin opens them).
  • Advice runs in the proxy, around the whole call, including any internal calls the target makes to itself.

Full AspectJ removes these limits by weaving at compile time or when classes are loaded (with a Java agent). It is rarely needed in Spring applications, but good to know when you hit one of the walls above.

When to write your own aspect

Spring's built-in aspects (@Transactional, @Cacheable, @Async, @PreAuthorize, @Retryable) cover most needs. Writing your own makes sense for genuinely cross-cutting, uniform behavior: timing and metrics (although Micrometer's @Timed and @Observed already exist; see Actuator, Metrics and Observability), audit logging, enforcing a team-wide rule such as "repositories must not be called from controllers", or tenant checks.

Avoid aspects for business logic. "When an order is placed, send an email" belongs in the order code (or in an event listener), where readers can find it. An aspect that quietly changes arguments or return values is hard to debug, and nobody reading the method will suspect it is there.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which kind of advice can decide not to call the target method at all and return a value of its own?

    Around advice controls the call through proceed(). If it never calls proceed(), the target method doesn't run. Caching works this way.
  2. 2. Spring creates a JDK dynamic proxy for CatalogPriceService implements PriceService. Another bean has a constructor parameter of type CatalogPriceService. What happens?

    A JDK proxy only implements the interfaces. That's one reason Spring Boot uses CGLIB subclass proxies by default.
  3. 3. A bean's non-transactional method payAll() calls its own @Transactional method transfer(). What happens when a caller invokes payAll()?

    Self-invocation uses this, the raw object, so the transactional advice never runs. Move transfer() to another bean or make the outer method transactional.
  4. 4. What does the pointcut @annotation(com.example.shop.Timed) select?

    @annotation matches method executions where the method carries the given annotation. @within would match by an annotation on the class.
  5. 5. Logging advice has @Order(1) and timing advice has @Order(2). Both apply to reserve(). In what order do things happen?

    The lowest order value is the outermost layer of the interceptor chain, so logging wraps timing, which wraps the method.

Summary

  • Cross-cutting concerns (logging, timing, transactions, security, caching, retries) would otherwise be duplicated across many classes. AOP writes them once.
  • An aspect contains advice (@Before, @AfterReturning, @AfterThrowing, @After, @Around) applied at join points (method executions) selected by pointcuts such as execution(...), within(...) and @annotation(...).
  • Spring weaves aspects at runtime with proxies: JDK dynamic proxies for interfaces, CGLIB subclasses otherwise (Spring Boot's default). Several advices form an interceptor chain ordered by @Order.
  • java.lang.reflect.Proxy and an InvocationHandler are enough to build timing, logging and transactional proxies yourself.
  • Advice runs only for calls through the proxy: self-invocation, private/final/static methods and objects created with new are not advised.
  • @Transactional, @Cacheable, @Async and @PreAuthorize are all aspects. Use custom aspects for uniform technical concerns, not for business logic.

Next: Spring JDBC with JdbcTemplate and JdbcClient.