gpt4 book ai didi

java - 在拦截方法上配置拦截器(代理)

转载 作者:行者123 更新时间:2023-12-01 14:42:54 27 4
gpt4 key购买 nike

据我所知,在Spring AOP中,当我们想要拦截某些方法调用时,我们会配置一个具有与所需方法调用相匹配的切入点配置的Aspect。也就是说,我们在Aspect端配置拦截。

有没有一种方法可以完全从相反的一侧配置它,即在要拦截哪个调用的方法上配置它?我希望这样的事情是可能的:

@Component
class MyClass {
@Intercept(interctptor="myInterceptor", method="invoke")
Object methodThatWillBeIntercepted(Object arg) {
// ..
}
}

@Component(value="myInterceptor")
class MyInterceptor {
Object invoke(MethodInvocation mi) {
// ...
if (someCondition) {
return mi.proceed();
} else {
return someOtherValue;
}
}
}

最佳答案

你可以,至少如果你将它与 AspectJ 一起使用的话。您可以在切入点声明中使用语法 @annotation(com.mycompany.MyAnnotation) 来定位使用您的注释进行注释的元素。您可以在section 9.2.3 of the Spring reference documentation中阅读更多相关信息。

如果您没有使用 AspectJ,而是使用基于通用代理的拦截器,则“强力”方法将代理您想要检查的所有对象,然后检查方法调用参数以查看该方法是否带有注释您的注释,如下所示:

class MyInterceptor {
public Object invoke(MethodInvocation mi) {
if(mi.getMethod().getAnnotation(MyAnnotationClass.class) != null) {
// Do the interception
}
else {
return mi.proceed();
}
}
}

不记得 MethodInvocation 的确切 API,但类似的东西。

关于java - 在拦截方法上配置拦截器(代理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15763656/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com