Pointcuts
Pointcut EXPRESSION hai jo DEFINE karta hai KAUN SE JOIN POINTS (method calls) par ADVICE apply hogi. execution() SABSE COMMON pointcut designator hai — method signature PATTERN match karta hai. @annotation() sirf SPECIFIC ANNOTATION wale methods TARGET karta hai. within() ek PACKAGE/CLASS ke ANDAR SAARE methods TARGET karta hai.
Pointcut expressions ko EK ALAG, NAMED method mein DEFINE karके, MULTIPLE advice ke beech REUSE kiya ja sakta hai — DRY principle. Isse pointcut definition EK JAGAH maintain hoti hai, agar CHANGE karna ho to SAB advice AUTOMATICALLY UPDATE ho jaati hain.
@Aspect
@Component
public class ServiceAspect {
// Reusable, named pointcut:
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayer() { }
@Before("serviceLayer()")
public void logEntry() {
System.out.println("Entering service method");
}
@AfterReturning("serviceLayer()")
public void logSuccess() {
System.out.println("Service method completed");
}
}
// Sirf specific annotation wale methods target karna:
@Before("@annotation(com.example.LogExecution)")
public void logAnnotated() { }- execution() = method signature pattern match karta hai
- @annotation() = specific annotation wale methods target karta hai
- Named pointcuts = reusable, DRY principle follow karte hain
Pointcut expressions WHERE advice apply hogi define karte hain — execution(* com.example.service.*.*(..)) matlab "service package ke ANDAR, kisi bhi class ke, kisi bhi method par". @annotation(com.example.LogExecution) matlab "sirf UN methods par jinpe @LogExecution annotation lagा hai".
// Saare methods, service package mein:
@Pointcut("execution(* com.example.service.*.*(..))")
// Sirf @LogExecution annotation wale methods:
@Pointcut("@annotation(com.example.LogExecution)")
// Sirf specific package + Repository suffix wali classes:
@Pointcut("within(com.example.repository..*Repository)")Pointcut expressions ko EK ALAG method mein DEFINE karके, MULTIPLE advice mein REUSE kiya ja sakta hai — DRY principle follow karta hai, aur pointcut expression EK JAGAH maintain hoti hai.
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayer() { } // named pointcut, koi body nahi
@Before("serviceLayer()")
public void logBefore() { }
@AfterThrowing("serviceLayer()")
public void logException() { }