Spring AOP 切入点由参数区分

Spring AOP pointcut differentiated by arguements

我在相同的 class 中有两个 public 方法,具有相同的 return 类型,唯一不同的是它采用的参数。我只想在其中一个应用切入点。

这里是class的例子:

public class HahaService{

    public MyObject sayHaha(User user){
        //do something
    }

    public MyObject sayHaha(Long id, User user){
        //do something
    }
}

现在我想让一个切入点只应用于第二个 sayHaha 方法,它有两个参数:一个 Long id 和一个 User 用户。

我目前有一个@Pointcut

@Pointcut("execution(public MyObject com.abc.service.HahaService.sayHaha(..))")
private void hahaPointCut() {
}

此切入点应用于两个 sayHaha 方法。

有没有办法只在第2次做?

是的,只需将切入点表达式限制为具有特定参数类型的方法。

去掉..并指定参数类型

@Pointcut("execution(public MyObject com.example.HahaService.sayHaha(Long, com.example.User))")

或者,如果您确实需要参数的值,您可以使用名称绑定来捕获它们。例如,您的切入点将声明为

@Pointcut("execution(public MyObject com.example.HahaService.sayHaha(..)) && args(id, user)")
private void hahaPointCut(Long id, User user) {
}

并且建议,例如 @Before,将声明为(重复名称)

@Before("hahaPointCut(id, user) ")
public void before(Long id, User user) {
    /* execute advice */
}

现在Spring AOP可以通过切入点中的参数与args中使用的名称之间的匹配来确定参数的类型。然后它匹配 @Before 中的那些并绑定到相应的调用参数。

此技术在 Passing parameters to advice 的章节中进行了描述。