AOP (Aspect-Oriented Programming) tách cross-cutting concern (logging, security, transaction, metrics) khỏi business logic.
Khái niệm: Aspect (module chứa logic), Pointcut (chọn method bị intercept), Advice (@Before/@After/@Around/@AfterThrowing), JoinPoint (điểm thực thi cụ thể).
java
@Aspect @Component
class LoggingAspect {
@Pointcut("execution(public * com.example.service.*.*(..))")
void serviceLayer() {}
@Around("serviceLayer()") // bao quanh method
Object logTime(ProceedingJoinPoint pjp) throws Throwable {
long start = System.currentTimeMillis();
try { return pjp.proceed(); } // gọi method thật
finally { log.info("{} in {}ms", pjp.getSignature().getName(), System.currentTimeMillis() - start); }
}
}Pointcut expression phổ biến: execution( com.example.service..*(..)) (mọi method trong package), @annotation(Transactional) (method có annotation), within(...), args(Long, ..).
Lưu ý: Spring Boot tự bật AOP khi có spring-boot-starter-aop — không cần @EnableAspectJAutoProxy. AOP chạy qua proxy (giống @Transactional) → self-invocation không được intercept.