Sub topic 8
Enabling AOP and writing your first aspect
This chapter shows how to turn on Spring AOP and write a working aspect. It assumes you know core Java (interfaces, inheritance, annotations), basic Spring dependency injection (beans, @Component, @Configuration), and a little reflection. It also assumes you have seen the AOP vocabulary: aspect, join point, pointcut, and advice. Later chapters cover pointcut syntax and the advice types in depth. Here you get a first aspect running and learn the common reasons it fails to run.
What "enabling AOP" actually does
Spring AOP does nothing until something asks it to. That something is a bean post-processor, a hook that runs on each bean after the container creates it. When AOP is on, Spring registers an auto-proxy creator (AnnotationAwareAspectJAutoProxyCreator). For each bean, the creator does the following:
- It finds every
@Aspectbean in the container. - It checks whether any pointcut matches a method on the bean.
- If at least one does, it replaces the bean with a proxy that runs the advice. If none match, the original bean is left alone.
The bean you inject elsewhere is therefore the proxy, not your original object. Later chapters on proxy creation and debugging build on this fact.
Turning it on
You have two options.
- Plain Spring: add
@EnableAspectJAutoProxyto a@Configurationclass. - Spring Boot: add
spring-boot-starter-aopto the classpath. Boot's auto-configuration enables AOP for you, so the annotation is not needed.
You also need the AspectJ annotation library (aspectjweaver) on the classpath. The Boot starter brings it in. Spring AOP uses AspectJ's annotations and its pointcut expression language, but it does not use AspectJ's weaving. It still creates proxies at runtime.
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
class AopConfig {
}@EnableAspectJAutoProxy has an attribute, proxyTargetClass. When it is true, Spring always uses CGLIB (class-based) proxies. When it is false, Spring uses a JDK proxy if the bean implements an interface. Spring Boot sets it to true by default, so a Boot application usually gets CGLIB proxies even for beans that have interfaces.
Your first aspect
An aspect is a class annotated with @Aspect. The annotation alone does not make it a bean, so you must also register it, usually with @Component.
This aspect times every method in the com.example.service package and its subpackages:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimingAspect {
@Around("execution(* com.example.service..*(..))")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try {
return pjp.proceed();
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(pjp.getSignature().toShortString() + " took " + ms + " ms");
}
}
}Each part has a role:
| Part | Role |
|---|---|
| `@Aspect` | Marks the class as holding advice and pointcuts. |
| `@Component` | Makes the aspect a Spring bean so the container finds it. |
| `@Around(...)` | Declares advice that wraps the method call. |
| `execution(* com.example.service..*(..))` | The pointcut: any method, any return type, any arguments, in `com.example.service` or below. |
| `ProceedingJoinPoint` | A handle on the intercepted call. Calling `proceed()` runs the next advice or the real method. |
| `finally` block | Records the time even if the target throws. |
The throws Throwable clause and the return of proceed()'s result both matter. If you forget to return the result, the caller receives null. If you catch exceptions and swallow them, you change the behavior of the target. Around advice is covered in depth in its own chapter.
Seeing it run
Suppose this service lives in com.example.service:
package com.example.service;
import org.springframework.stereotype.Service;
@Service
public class PriceService {
public double priceFor(String sku) {
return sku.length() * 1.5;
}
}When another bean calls priceService.priceFor("ABC"), the call goes to the proxy first. The aspect starts the timer, calls the real method, and prints a line like PriceService.priceFor(..) took 0 ms.
Common errors when nothing happens
If the advice does not run, check these causes in order.
- The aspect is not a bean.
@Aspectwithout@Component(or a@Beanmethod, or a component scan that reaches it) is silently ignored. - AOP is not enabled. In plain Spring there is no
@EnableAspectJAutoProxy. In Boot, the starter is missing, so@Aspecthas no effect. - The target is not a Spring bean. Objects created with
neware never proxied. - The pointcut does not match. A wrong package or a typo is the usual cause. A pointcut that matches nothing is not an error.
- The call bypasses the proxy. Calls from one method to another on the same object (
this.other()) do not go through the proxy. This is the self-invocation problem, covered in a later chapter. - The method cannot be overridden or intercepted. Spring AOP applies advice only to public methods called through the proxy (by default). Final and private methods are not intercepted. A later chapter covers these limits.
A quick way to check that a bean was proxied is to print its class name. A proxied bean usually has a name like PriceService$$SpringCGLIB$$0, or a JDK proxy name such as jdk.proxy2.$Proxy45. A plain com.example.service.PriceService means no proxy was created.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
class ProxyCheck implements CommandLineRunner {
private final com.example.service.PriceService priceService;
ProxyCheck(com.example.service.PriceService priceService) {
this.priceService = priceService;
}
@Override
public void run(String... args) {
System.out.println(priceService.getClass().getName());
priceService.priceFor("ABC");
}
}Edge cases to know now
- An aspect does not advise itself. Spring excludes
@Aspectbeans from auto-proxying. A pointcut cannot make advice run on another aspect's methods. - Return types and
proceed(). For a method that returnsvoid,proceed()returnsnull. Returning it unchanged is correct. - Primitive returns. If the target returns a primitive such as
doubleand your advice returnsnull, Spring throws an exception when it unboxes the value. Always return whatproceed()returned unless you intend to replace it. - Exceptions. Because the advice declares
throws Throwable, checked exceptions from the target pass through unchanged. If you wrap them, the caller sees a different exception type. - Overhead. Each advised call adds a proxy hop and advice execution. This is small for service-layer methods, but avoid advising hot, tiny methods that run millions of times.
Exercise
You add @Aspect to a class named LoggingAspect with a valid @Around pointcut, and your Spring Boot app has spring-boot-starter-aop. The advice never runs. Name the most likely missing piece, and explain how you would confirm that a target bean is being proxied.
Show answer
The class is most likely not registered as a bean, because @Aspect alone does not make it one. Add @Component (or declare it with @Bean). To confirm that a target bean is proxied, inject it somewhere and print getClass().getName(). A proxied bean shows a name containing $$SpringCGLIB$$ or a JDK $Proxy name. A plain class name means no proxy exists, so the problem is the pointcut or the target not being a Spring bean.
Exercise
In the TimingAspect above, what happens to the caller if you replace return pjp.proceed(); with a bare call pjp.proceed(); followed by return null;, when the target method returns double?
Show answer
The real method still runs, but the advice discards its result and returns null. Spring then fails to convert null into a primitive double, so the caller gets an exception instead of the price. Always return the value from proceed() unless you deliberately replace it.