Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 66 ยท Inversion of Control and Beans

Aspects in Spring Boot (AOP)

Add logging, timing and security checks to many beans without touching their code: Spring AOP in Boot, pointcuts, advice types, weaving, proxies and AspectJ.

Some concerns cut across your whole application. Every service method should be logged and timed, every repository call should run in a transaction, every controller method should be checked for permission. If you write that code inside each method, the real logic disappears under repetition. Aspect-oriented programming (AOP) pulls such a cross-cutting concern out into one place, an aspect, and tells Spring which methods it applies to. Transactions (@Transactional), caching (@Cacheable), method security (@PreAuthorize), retries and @Async are all aspects that ship with Spring, so knowing how they work explains a lot of Boot behavior.

This lesson shows how to write your own aspect in a Boot application and, with a runnable stand-in built on java.lang.reflect.Proxy, how Spring applies it. The real Spring and AspectJ annotations are read-only here because Spring is not on this site's Java runner. For the deeper treatment (advice order, self-invocation, XML configuration), continue with Aspect-Oriented Programming in the Advanced Java tutorial.

The vocabulary

AOP in four words

Pointcut Which methods to match.
Advice What to run around them.
Aspect A pointcut plus its advice.
Weaving Wrapping the target with the aspect.

Spring weaves with proxies, at startup.

1 / 2
Term Meaning
Join point A point in the program where advice can run. In Spring AOP it is always a method execution on a Spring bean.
Pointcut An expression that selects join points, such as "every public method in the service package".
Advice The code that runs at a join point: before, after returning, after throwing, after (finally), or around.
Aspect A class that combines pointcuts and advice.
Target The bean being advised (your service).
Proxy The object Spring puts in front of the target; callers get the proxy.
Weaving Linking aspects to targets. Spring AOP weaves at runtime by creating proxies. Full AspectJ can also weave at compile time or class-load time.

Adding AOP to a Boot project

Add the AOP starter. Boot's auto-configuration then switches proxying on for you, so you do not write @EnableAspectJAutoProxy yourself:

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

(In Boot 4 the starter is named spring-boot-starter-aspectj; the annotations are the same. Check the name for your version on start.spring.io.) An aspect is a normal bean: annotate it with @Aspect and @Component.

Java
@Aspect
@Component
class TimingAspect {

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

    // pointcut: every public method of every class in a package named "service"
    @Pointcut("execution(public * com.example.shop..service..*(..))")
    void serviceMethods() { }

    @Before("serviceMethods()")
    void logCall(JoinPoint jp) {
        log.debug("calling {}", jp.getSignature().toShortString());
    }

    @AfterReturning(pointcut = "serviceMethods()", returning = "result")
    void logResult(JoinPoint jp, Object result) {
        log.debug("{} returned {}", jp.getSignature().getName(), result);
    }

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

    @Around("serviceMethods()")
    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);
        }
    }
}

The execution(...) expression reads execution(modifiers? return-type declaring-type? name(params) throws?), and * and .. are wildcards (.. in a package means "any depth", in a parameter list "any arguments"). Other designators you will meet:

Designator Matches
within(com.example.shop.service.*) every method in the types of a package
@annotation(com.example.Timed) methods that carry the annotation
@within(org.springframework.stereotype.Service) methods of classes that carry the annotation
bean(*Service) beans whose name matches (Spring-specific)
args(Long, ..) methods whose first argument is a Long

You can combine them with &&, || and !. Matching by a custom annotation is the cleanest style for your own aspects, because the method itself says "this is timed":

Java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Timed { }

@Around("@annotation(Timed)")
Object time(ProceedingJoinPoint pjp) throws Throwable { /* as above */ }

How Spring weaves: proxies

Spring does not edit your classes. At startup, after it creates the BookService bean, a bean post-processor checks whether any pointcut matches it. If so, the container replaces the bean with a proxy: a generated object of the same type (a JDK dynamic proxy when the bean implements an interface, a CGLIB subclass otherwise; Boot defaults to CGLIB through spring.aop.proxy-target-class=true). Everything that gets the bean injected receives the proxy. A call goes caller, proxy, advice chain, target.

flowchart LR
    C["Caller"] --> P["Proxy<br/>(advice chain)"]
    P -->|"@Before / @Around"| T["Target bean"]
    T -->|"return or throw"| P
    P -->|"@AfterReturning / @AfterThrowing / @After"| C

The caller never sees the target directly, which is why a call that bypasses the proxy bypasses the aspect.

The first TryIt rebuilds that mechanism. weave wraps a target in a JDK proxy; the "pointcut" is a predicate over the method, and the "advice" runs before, after returning, after throwing and finally. Spring does the same with more machinery. What is real: the proxy, the pointcut-then-advice flow and the rule that unmatched methods pass straight through. What is simplified: one hard-coded aspect and no ordering.

Java A proxy that weaves logging advice

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.

An annotation-driven @Around aspect

@Around is the most powerful advice: it receives a ProceedingJoinPoint, decides whether to call proceed() at all, can change the arguments or the result, and can catch exceptions. Timing, retrying, caching and permission checks are all @Around aspects. The second TryIt builds an annotation-driven one: methods marked @Timed are reported, methods marked @Retry(times) are re-run when they throw. This is the same shape as Spring's own @Cacheable and @Retryable (see Resilience).

Java @Timed and @Retry as around advice

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.

Because aspects work through the proxy, a method that calls another method on this skips the advice: the call never leaves the target. This is the well-known reason a @Transactional or @Cacheable method has no effect when another method of the same class calls it. Put the advised method in another bean, or inject the proxy. Also remember that Spring AOP only advises public methods of Spring beans called from outside, and cannot advise final classes or methods, or private methods.

Spring AOP or full AspectJ?

Spring AOP (this lesson) is proxy-based, covers method execution on beans, needs no special build, and is enough for nearly all application code. AspectJ is a complete AOP language and compiler (with a load-time weaver) that can advise constructors, field access, static methods and objects that are not Spring beans, and has no self-invocation problem, at the cost of a special build step (the AspectJ compiler or a weaving agent). Spring reuses AspectJ's annotation style and expression language (@Aspect, @Pointcut), so aspects you write today can move to AspectJ weaving later. Other AOP frameworks such as JBoss AOP exist, but Spring AOP and AspectJ are the ones you will meet.

Aspect order

When several aspects match one method, they form a chain. Control the order with @Order(n) on the aspect class: the lowest number runs first on the way in and last on the way out. A typical order is security first, then retry, then timing, so each layer wraps the next. Transaction management sits at the lowest precedence by default, so your own aspects run outside the transaction unless you say otherwise.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a pointcut do?

    A pointcut is a matching expression. The advice is the code that runs at the matched join points.
  2. 2. Which advice runs only when the advised method throws an exception?

    @AfterThrowing runs after an exception. @After runs in every case, like a finally block.
  3. 3. How does Spring AOP apply an aspect to a bean?

    Weaving in Spring AOP happens at startup by wrapping the bean in a JDK or CGLIB proxy.
  4. 4. Why does a @Transactional method have no effect when another method in the same class calls it?

    The advice lives in the proxy. A call on this never passes through it.

Summary

  • An aspect combines a pointcut (which methods) with advice (what to run): @Before, @AfterReturning, @AfterThrowing, @After and @Around.
  • Add the AOP starter; Boot enables proxying automatically. Aspects are beans marked @Aspect and @Component.
  • Spring weaves by replacing beans with JDK or CGLIB proxies, so only calls that cross the proxy are advised, and self-invocation is not.
  • execution, within, @annotation, @within, bean and args are the common pointcut designators; annotation-based pointcuts are the clearest for your own aspects.
  • Use @Order to control how multiple aspects wrap each other. Choose full AspectJ only when you need to advise more than bean method calls.

Next: Auto-Configuration Explained.