AspectJ之Execution表达式
Execution表达式语法
在AspectJ中,Execution表达式用于定义切点,即指定在何处应用切面逻辑。Execution表达式可以在AspectJ注解或XML配置中使用。
Execution表达式的语法如下:
1 | execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?) |
语法说明:带?的部分表示可省略,只看必须参数的话,语法如下:
1 | execution(ret-type-pattern name-pattern(param-pattern)) |
Execution表达式的各个部分的说明:
modifiers-pattern
:可选项,用于指定方法的修饰符模式,如public
、private
、protected
等。ret-type-pattern
:可选项,用于指定方法的返回类型模式,如void
、int
、java.util.List
等。可以使用*
通配符匹配任意返回类型。declaring-type-pattern
:可选项,用于指定方法所在类的模式。可以使用*
通配符匹配任意类。name-pattern
:用于指定方法名的模式,可以使用*
通配符匹配任意方法名。param-pattern
:用于指定方法参数的模式。可以使用*
通配符匹配任意参数类型,也可以使用..
表示匹配任意数量的参数。throws-pattern
:可选项,用于指定方法抛出异常的模式。
从语法各部分的说明可以看出,execution表达式可以只带有 方法的返回类型 + 方法名 + 方法参数 ,这也是Java方法定义的最基本元素。
Execution扩展语法
关于AspectJ的Execution表达式的一些额外细节:
- 通配符(Wildcards):Execution表达式中的通配符
*
用于匹配任意字符或任意数量的字符。可以在修饰符、返回类型、类名、方法名和参数类型等位置使用通配符来进行模式匹配。例如,execution(public * *(..))
匹配所有公共方法,execution(* com.example.*.*(..))
匹配指定包名下的所有方法。 - 参数模式(Parameter Patterns):Execution表达式中的参数模式用于指定方法的参数类型。可以使用具体的类型来匹配特定的参数,也可以使用通配符
*
匹配任意类型。另外,使用..
表示匹配任意数量的参数。例如,execution(* *(com.example.MyClass))
匹配具有一个类型为com.example.MyClass
的参数的所有方法,execution(* *(..))
匹配任意参数类型的方法。 - 异常模式(Exception Patterns):Execution表达式中的异常模式用于指定方法可能抛出的异常类型。可以使用具体的异常类型进行匹配,也可以使用通配符
*
匹配任意异常类型。例如,execution(* *(..) throws Exception)
匹配所有可能抛出Exception
类型异常的方法。 - 组合模式(Combining Patterns):Execution表达式允许将多个模式组合在一起,以便更精确地匹配方法。可以使用逻辑运算符
&&
(与)、||
(或)和!
(非)来组合不同的模式。例如,execution(public * *(..)) && !execution(* get*(..))
匹配所有公共方法,但排除以"get"开头的方法。
Execution常用表达式
-
匹配所有公共方法:
1
execution(public * *(..))
-
匹配返回类型为
int
的所有方法:1
execution(int * *(..))
-
匹配指定类中的所有方法:
1
execution(* com.example.MyClass.*(..))
-
匹配指定类及其子类中的所有方法:
1
execution(* com.example.MyClass+.*(..))
-
匹配指定方法名以"get"开头的方法:
1
execution(* get*(..))
-
匹配指定参数类型的方法:
1
execution(* *(com.example.MyClass))
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 WrayのBlog!
评论