据我所知,在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;
}
}
}
答案 0 :(得分:1)
至少如果你在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,但有类似的东西。