Spring AOP
Spring AOP is the form of aspect-oriented programming most Java developers actually use. It ships with the Spring framework, needs no special compiler, and uses annotations and the AspectJ pointcut language. Spring wraps your beans in proxies that run the advice around each call.
Paradigm: Aspect-Oriented Programming
What Makes Spring AOP Special
- Proxy-based weaving. At startup Spring creates a proxy around each matching bean. A call goes through the proxy, which runs advice before and after the real method.
- Uses AspectJ syntax. You write
@Aspectclasses with@Before,@Afterand@Aroundadvice and AspectJ pointcut expressions, without the AspectJ compiler. - Declarative services are aspects.
@Transactional,@Cacheable,@Asyncand method security are all implemented as aspects, so you are using AOP even if you never write one. - Limited to Spring beans and method calls. Only calls to public methods on Spring-managed beans that arrive through the proxy are advised. A call from inside the same class (
this.foo()) is not intercepted. - Easy to enable. Spring Boot turns it on automatically, and outside Boot you add
@EnableAspectJAutoProxy.
Example: Timing every service method
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.bank..*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() + " took " + ms + " ms");
}
}
}
How It Works
@Aspectmarks the class as an aspect and@Componentlets Spring find and manage it.- The pointcut expression matches every method of every class whose name ends in
Servicein thecom.example.bankpackages. @Aroundadvice receives aProceedingJoinPoint. Callingproceed()runs the real method; code before and after it is the cross-cutting behavior.- The
finallyblock reports the duration even when the method throws. No service class was edited to add this.
History and Where It Is Used
Spring AOP appears in almost every Spring application through transactions, security, caching and metrics. When you need field access, constructor interception or calls inside the same class, teams switch to full AspectJ weaving, which Spring also supports.