aop注解默认扫描路径是当前包和子包
1. 拦截指定包中的所有方法调用:
@Pointcut("execution(* com.example.service.*.*(..))") public void serviceMethods() {}
2.拦截指定类中的所有方法调用:
@Pointcut("within(com.example.service.MyService)") public void myServiceMethods() {}
3.拦截带有特定注解的方法调用:
@Pointcut("@annotation(com.example.annotations.Loggable)") public void loggableMethods() {}
4.拦截符合多个条件的方法调用:
@Pointcut("execution(* com.example.service.*.*(..)) && @annotation(com.example.annotations.Loggable)") public void combinedMethods() {}
除了切点表达式,还可以在 Pointcut 声明的方法内使用其他注解、条件判断等语法,来更加精确地定义拦截规则
5.使用逻辑操作符(例如 &&、||、!):可以使用逻辑操作符组合多个切点条件,以便更精确地选择要拦截的
@Pointcut("execution(* com.example.service.*.*(..)) && !execution(* com.example.service.InternalService.*(..))") public void serviceMethods() {}
6.使用参数匹配:可以使用参数匹配的语法,在切点表达式中指定具体的方法参数类型或参数值。
@Pointcut("execution(* com.example.service.MyService.*(..)) && args(java.lang.String)") public void stringMethods() {}
7.使用引用其他切点:可以在切点表达式中引用其他已声明的切点,以实现切点的复用和组合。
@Pointcut("execution(* com.example.service.UserService.*(..))")
public void userMethods() {}
@Pointcut("execution(* com.example.service.OrderService.*(..))")
public void orderMethods() {}
@Pointcut("userMethods() || orderMethods()")
public void userOrOrderMethods() {}
8.使用静态方法引用:在切点表达式中,可以引用静态方法来进行复杂的逻辑运算和条件判断。
@Pointcut("execution(* com.example.service.*.*(..)) && (@annotation(com.example.annotations.Loggable) || hasRole('ADMIN'))")
public void loggableOrAdminMethods() {}
public static boolean hasRole(String role) {
// 进行角色判断逻辑
}
9.使用通配符:可以在切点表达式中使用通配符来匹配方法的名称或参数类型。常用的通配符有"*“(匹配任意字符)和”…"(匹配任意参数)。
@Pointcut("execution(* com.example.service.*Service.*(..))")
public void serviceMethods() {}