SpringAOP-切点表达式

一、execution 表达式

语法格式

execution([修饰符] 返回类型 [类全路径].方法名(参数列表) [throws 异常])

示例

// 匹配所有方法
execution(* *(..))

// 匹配特定包下的所有方法(不会递归,当前包合当前包的子包)
execution(* com.example.service.*.*(..))
  
// 匹配特定包下的所有方法(会递归)
execution(* com.example.service..*.*(..))
  
// 匹配特定类的方法
execution(* com.example.service.UserService.*(..))

// 匹配特定类及其子类的所有方法
execution(* com.example.service.BaseService+.*(..))
  
// 匹配所有包中的 getUser 方法
execution(* *.getUser(..))

// 匹配特定类中 find 开头的方法
execution(* * com.example.service.UserService.find*(..))

// 匹配返回 String 的所有方法
execution(String *(..))

// 匹配参数个数不限,第一个参数为 String 的方法
execution(* *(String, ..))

// 匹配两个参数,第一个为 String,第二个为 int 的方法
execution(* *(String, int))

// 匹配任意数量参数,但第一个必须是 Long 的方法
execution(* *(Long, ..))

// 匹配所有 public 方法
execution(public * *(..))

// 匹配所有 private 方法(仅 AspectJ 支持,Spring AOP 不支持)
execution(private * *(..))
  
// 匹配特定包下抛出 Exception 的方法
execution(* com.example.service.UserService.*(..) throws Exception)

二、within 表达式

  • execution 具有 within 的功能
  • within 只能匹配包或类,不能匹配方法、返回值、修饰符、参数、异常

语法格式

within(范围)

示例

// 匹配 UserService 类的所有方法
within(com.example.service.UserService)

// 匹配 UserService 类及其子类的所有方法
within(com.example.service.UserService+)

// 匹配 com.example.service 这个包及其子包下的所有类(不会递归)
within(com.example.service.*)

// 匹配 com.example.service 这个包及其子包下的所有类(会递归)
within(com.example.service..*)

// 同上(这时的 * 被省略了)
within(com.example.service..)

三、@annotation 表达式

// 匹配标注了 @GetMapping 注解的方法
@annotation(org.springframework.web.bind.annotation.GetMapping)

四、组合表达式

// AND
@Pointcut("execution(* com.example.service.*(..)) && within(com.example.service.UserService)")

// OR
@Pointcut("execution(* com.example.service.*(..)) || execution(* com.example.repository.*(..))")

// NOT
@Pointcut("execution(* com.example.service.*(..)) && !execution(* com.example.service.UserService.*(..))")
posted @ 2024-11-02 20:37  CyrusHuang  阅读(31)  评论(0)    收藏  举报