春季AOP切入点通过参数区分



我在同一类中有两个具有相同返回类型的公共方法,只是它采用的参数不同。我想只对其中一个应用切入点。

下面是该类的示例:

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方法。

有没有办法只能在第二个上做到这一点?

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

摆脱..并指定参数类型

@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中的参数,并绑定到相应的调用参数。

此技术在将参数传递给建议一章中进行了描述。

相关内容

最新更新