Why this matters
- Copy-pasting logging or timing code into every service method violates DRY and clutters business logic.
- Spring's
@Transactionaland@Cacheableare themselves AOP proxies — understanding AOP explains how they work. - Custom aspects handle BookStore-specific concerns like audit trails and performance monitoring.
Cross-cutting concerns
L1 · FresherLogging, metrics, and security repeat across services — AOP centralizes them in aspects instead of copy-paste.
Advice types
L2 · Intermediate@Before, @After, @Around run at join points matched by pointcut expressions like @annotation(Timed).
Proxy vs AspectJ
L3 · AdvancedSpring AOP uses JDK/CGLIB proxies — only public method calls on Spring beans are advised. Self-invocation is not advised.
Prefer Micrometer
L4 · ExpertUse @Timed and observation API for metrics where possible; custom aspects for domain auditing with clear pointcuts.
Enable AOP
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Spring Boot auto-configures AOP when the starter is present.
A logging aspect
// learn:fragment
@Aspect
@Component
public class LoggingAspect {
private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);
@Before("execution(* com.example.bookstore.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Calling {}.{}()",
joinPoint.getTarget().getClass().getSimpleName(),
joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "execution(* com.example.bookstore.service.*.*(..))",
returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
log.debug("{}.{}() returned {}",
joinPoint.getTarget().getClass().getSimpleName(),
joinPoint.getSignature().getName(),
result);
}
}
Every BookService, OrderService, etc. method is logged without touching their code.
Advice types
@Before— Runs before the method. Logging, argument validation.@AfterReturning— Runs after successful return. Result logging, metrics.@AfterThrowing— Runs when the method throws. Error logging, alerting.@After— Runs after method completes (success or failure). Cleanup.@Around— Wraps the method entirely. Timing, retry, transaction control.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- @Around for execution timing
- Pointcut expressions
- Custom annotation + aspect
- How proxies work
- AOP vs manual cross-cutting
Test yourself
Answer these before moving on — recall is what makes it stick.