spring aop Pointcut切入点表达式:within和execution

说明

within表达式 和 execution表达式,主要作用相同,都是定义 切入点规则 的,区别:

  • execution表达式细粒度,可以针对 方法 定义切入点规则
  • within表达式粗粒度,只能对 类 定义切入点规则

execution 表达式(常用)

细粒度 的切入点表达式,可以根据 包名、类名、方法名、返回值、形参 定义切入点规则

提示:可以实现 within表达式 的所有功能

表达式

execution( * *..*.*(..) )

能够匹配上面表达式的方法,就会被注入代码

说明:

表达式的部分 说明
第1个* 表示 任意返回值 (包括void)
*.. 表示当前 包 及其 子包
第3个* 表示任意类名
第4个* 表示任意方法名
最后 .. 任意形参

例子

  1. 所有 public 方法都会注入代码

    execution(public * *(..))
    
  2. 所有以 set 开头的公有方法都会注入代码

    execution(* set*(..))
    
  3. IUserService 接口下的所有方法都会注入代码

    execution(* top.malaoshi.service.IUserService.*(..))
    
  4. top.malaoshi.service 包下的所有方法都会注入代码

    execution(* top.malaoshi.service.*.*(..))
    
  5. top.malaoshi.service 包及其子包下的所有方法都会注入代码

    execution(* top.malaoshi.service..*.*(..))
    

within表达式

粗粒度 的切入点表达式,根据 包名、类名 定义切入点规则

表达式

within(*..*)

例子1

within(top.malaoshi.service.*)

解释:* 表示 top.malaoshi.service 包下所有的类

例子2

within(top.malaoshi.service.*.*)

第一个 * 表示一层包
第二个 * 表示该包下所有的类

例子3

within(top.malaoshi.service..*)

解释:表示 top.malaoshi.service 包下,及其子孙包下所有的类


原文出处:/show_1IX5m1UZDrTY.html