Sub topic 8
Enabling AOP and writing your first aspect
This chapter assumes you know core Java, basic Spring dependency injection (@Component, @Configuration), and annotations. You should also know that Spring wraps beans in proxies, which earlier chapters covered. Here you turn that mechanism on and write an aspect that times service methods.
Turning on proxy creation
Spring does not create AOP proxies by default. You enable it in one of two ways:
- Add
@EnableAspectJAutoProxyto a@Configurationclass. - In Spring Boot, add
spring-boot-starter-aop. Boot's auto-configuration then enables AOP for you.
Enabling AOP registers a bean post-processor. After each bean is created, the post-processor checks whether any aspect's pointcut matches the bean. If one does, Spring replaces the bean with a proxy that runs the advice and then delegates to the original object.
A first aspect
An aspect is a class annotated with @Aspect. It must also be a Spring bean, so add @Component. @Aspect alone does not register the class.
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
@Configuration
@EnableAspectJAutoProxy
class AopConfig {
}
@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");
}
}
}The class has two parts:
- The pointcut. The string
execution(* com.example.service..*(..))selects every method of every class incom.example.serviceand its subpackages. A later chapter covers the syntax. - The advice.
timeis@Aroundadvice. It receives aProceedingJoinPoint, which represents the intercepted call. Callingproceed()runs the real method. Code beforeproceed()runs before the method, and code after it runs afterward.
The finally block makes the timing print even when the target method throws. Declare throws Throwable and return the result of proceed(). If you swallow the exception or the return value, you change the behavior of the application.
What happens at runtime
The caller never sees the difference. It holds a reference typed as the bean's interface or class, but that reference points to the proxy.
Common errors
- No output at all. The aspect is missing
@Component, or AOP is not enabled, or the target bean is outside the pointcut's package. ClassNotFoundExceptionfororg.aspectj. The AspectJ annotations are not on the classpath. In Boot, addspring-boot-starter-aop. In plain Spring, addaspectjweaver.- Advice runs for some calls but not others. Calls from one method to another in the same class bypass the proxy. A later chapter covers this.
Exercise
You wrote a class with @Aspect and an @Around method, and the application starts without errors, but nothing is timed. Name two things to check.
Show answer
Check that the aspect class is also a Spring bean (for example, it has @Component), and that AOP is enabled (@EnableAspectJAutoProxy, or spring-boot-starter-aop in Boot). You should also confirm that the pointcut matches the package of the beans you call, and that the calls come from outside the bean.