我的问题的主要引用资料:
- 为 Google Guice 编写方法拦截器:http://code.google.com/p/google-guice/wiki/AOP
- MethodInterceptor 接口(interface)的 JavaDoc:http://aopalliance.sourceforge.net/doc/org/aopalliance/intercept/MethodInterceptor.html
- 关于 Java 注释的一般引用:http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html和 http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html
现在我的问题:
我正在编写一个严重依赖 Google Guice 来创建对象和处理依赖项注入(inject)的 Java 应用程序。我正在尝试使用拦截器在执行某些带注释的方法之前运行预处理代码。到目前为止,我已经能够使用 Guice 的指令在已注释的方法上成功地执行拦截器(使用 MethodInterceptor
接口(interface))。但是,我现在想编写将在参数注释 上执行的拦截器。
这是一个示例场景。首先,我创建自己的注释。例如::
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface MyParameterAnnotation {
}
接下来,我为这个注解编写自己的拦截器:
public class MyParameterAnnotationInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// Do some stuff
return invocation.proceed();
}
}
这是我打算如何使用 @MyParameterAnnotation
的示例:
public class ExampleObject {
public String foo(@MyParameterAnnotation String param) {
...
}
}
最后,我需要创建一个 Guice Injector 并使用它来创建 ExampleObject
的安装,否则我无法在该项目中使用方法拦截器。我配置 Injector,以便 MyParameterAnnotationInterceptor
绑定(bind)到 @MyParameterAnnotation
,如下所示:
final MethodInterceptor interceptor = new MyParameterAnnotationInterceptor();
requestStaticInjection(MyParameterAnnotationInterceptor.class);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(MyParameterAnnotation.class), interceptor);
当我按照上述步骤执行对 ExampleObject.foo()
的调用时,不幸的是,尽管参数被 @MyParameterAnnotation
标记,但拦截器并未执行。请注意,如果注释被放置在方法级别,这些类似的步骤将起作用。
这让我得出了两个可能的结论:要么 Guice 不支持将拦截器绑定(bind)到参数注释,要么我做的事情完全不正确(也许我应该为拦截器使用另一个 AOP 联盟接口(interface),例如 FieldInterceptor ,但我非常怀疑,因为 JavaDoc for Guice's AbstractModule 表明 bindInterceptor()
方法只能使用 MethodInterceptor
参数)。
尽管如此,非常感谢所有帮助我们的人:)
最佳答案
匹配器用于方法注释而不是方法参数注释。
Guice 没有为方法参数注释提供匹配器——您要么必须自己编写一个,要么使用其他方案。请注意,这是一个有点奇怪的用例——通常你可以摆脱
public class ExampleObject {
@MyAnnotation
public String foo(String param) {
...
}
}
对于上面的例子,你有正确的 Guice 拦截器配置。
关于java - 使用 Guice 为参数注释编写拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13677849/