1、切点表达式介绍
切点表达式(Pointcut Expression)是AOP中用于定义切入点的表达式。它指定了在哪些地方(哪些方法)执行切面逻辑。
一个切点表达式通常由以下几个组成部分构成:
1.execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?):
execution: 表示匹配方法执行。
modifiers-pattern(可选):表示方法的修饰符模式,如 public、private 等,默认为任意修饰符。
ret-type-pattern:表示方法的返回类型模式,如 void、int、java.util.List 等。
declaring-type-pattern(可选):表示方法所属的类的模式,如 com.example.MyClass。
name-pattern:表示方法名称模式,如 myMethod、*Method 等。
param-pattern:表示方法参数模式,如 (java.lang.String, int)、(..) 表示任意参数等。
throws-pattern(可选):表示方法抛出异常的模式,如 java.lang.Exception。
2.通配符:
*:匹配任意数量的字符(除了路径分隔符和参数分隔符)。
..:匹配任意数量的字符,包括路径分隔符和参数分隔符。
3.注解匹配:
@annotation(annotation-type):匹配被特定注解标记的方法。
@within(annotation-type):匹配所在类被特定注解标记的方法。
4.其他关键字:
args(type-pattern):匹配参数类型符合特定模式的方法。
target(type-pattern):匹配目标对象符合特定模式的方法。
this(type-pattern):匹配代理对象符合特定模式的方法。
bean(id-or-name-pattern):匹配Spring容器中Bean的命名模式。
2.切点表达式使用示例
模版:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?):
示例:
1.匹配特定类的所有方法:
execution(* com.example.MyClass.*(..)): 匹配 com.example.MyClass 类中的所有方法。
2.匹配某个包下所有类的所有方法:
execution(* com.example.*.*(..)): 匹配 com.example 包及其子包下所有类的所有方法。
3.匹配某个包及其子包下所有类的所有方法:
execution(* com.example..*.*(..)): 匹配 com.example 包及其所有子包下所有类的所有方法。
4.匹配特定类中的特定方法:
execution(* com.example.MyClass.myMethod(..)): 匹配 com.example.MyClass 类中的 myMethod 方法。
5.匹配特定类中以某个前缀开头的所有方法:
execution(* com.example.MyClass.somePrefix*(..)): 匹配 com.example.MyClass 类中以 somePrefix 开头的所有方法。
6.匹配特定类中返回类型为特定类型的方法:
execution(java.util.List com.example.MyClass.*(..)): 匹配 com.example.MyClass 类中返回类型为 java.util.List 的所有方法。
7.匹配特定类中带有特定参数类型的方法:
execution(* com.example.MyClass.myMethod(java.lang.String, int)): 匹配 com.example.MyClass 类中名为 myMethod,参数类型为 java.lang.String 和 int 的方法。
8.匹配特定注解标记的方法:
execution(@com.example.MyAnnotation * *(..)): 匹配被 com.example.MyAnnotation 注解标记的所有方法。