Video in progress

Junior 🌱 Spring

Explain the AOP concepts of aspect, advice, pointcut and join point.

A join point is a point where an aspect can attach (in Spring, a method call). A pointcut is an expression that says which join points to pick. Advice is the code that runs there. An aspect is the class that holds the pointcuts and advice.

📖 Answer

We'll see everything in one example:

@Aspect
@Component
class AuditAspect {                                   // ASPECT

    @Pointcut("execution(* uz.bank.payment..*Service.*(..))")
    void paymentServices() {}                         // POINTCUT

    @AfterReturning("paymentServices()")              // ADVICE type
    void audit(JoinPoint jp) {                        // JOIN POINT info
        log.info("bajarildi: {}", jp.getSignature().toShortString());
    }
}
  • A join point is a point in the execution of the program. In AspectJ it can be a field access or a constructor too, but in Spring AOP it's only the execution of a bean method.
  • A pointcut is a filter: "all methods of classes in the uz.bank.payment package whose names end with Service".
  • Advice is what and when: before, after, after an error or around.
  • An aspect is the module that holds all of this.
  • The target is the original object, and the proxy is the wrapper Spring creates.

You can also write a pointcut by annotation: @annotation(uz.bank.Audited), which matches only methods marked @Audited. In practice I prefer that. It's more precise than matching by package: if a package is renamed, the aspect doesn't silently stop working.