在面向切面编程(AOP)中,切入点(Pointcut)用于定义在哪些方法或代码段上应该应用切面的逻辑。切入点使用表达式来匹配目标方法的签名和执行位置。
在 Spring AOP 中,常用的切入点表达式是基于方法的 execution 表达式。execution 表达式由访问修饰符、返回类型、类名、方法名和参数列表组成,具体格式如下:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
其中,各个部分的含义如下:
modifiers-pattern(可选):指定方法的访问修饰符,如 public、private 等。ret-type-pattern:指定方法的返回类型,如 int、void 等。使用通配符 * 可表示任意返回类型。declaring-type-pattern(可选):指定方法所属的类名或包名。例如,com.example.*Service 表示匹配 com.example 包下的所有以 “Service” 结尾的类。name-pattern:指定方法名,可以使用通配符 * 表示任意方法名,如 get* 表示以 “get” 开头的方法。param-pattern:指定方法的参数列表。例如,(String, *) 表示第一个参数为 String 类型,第二个参数为任意类型。throws-pattern(可选):指定方法可能抛出的异常。以下是一些示例:
execution(public * com.example.service.UserService.*(..)):匹配 com.example.service.UserService 类中所有公共方法。execution(* com.example.service.*Service.find*(String)):匹配以 “Service” 结尾的类中以 “find” 开头且只有一个 String 参数的方法。execution(* com.example.dao..*.*(..)):匹配 com.example.dao 包及其子包下的所有方法。在实际使用时,你可以根据需要灵活构造切入点表达式来匹配符合条件的目标方法。