java - 使用 Guice 为参数注释编写拦截器

标签 java annotations aop guice interceptor

我的问题的主要引用资料:


现在我的问题:

我正在编写一个严重依赖 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/

相关文章:

java - 如何将项目添加到列表中?

java - 如何基于带注释的参数编写方面切入点

java - Aspectj @Around 切入Java中的所有方法

maven - 在 Maven 项目中放置方面的地方

java - 添加具有相同日期的 ArrayList 值

java - 在单个线程中安排多个任务

Java 注释处理器 : Usage & Applications

java - 将 Request 范围对象注入(inject) @Aspect

java - JPA 复合键与 ManyToOne 获取 org.hibernate.PropertyAccessException : could not set a field value by reflection setter of

java - 单元测试中@TestOnly和@VisibleForTesting有什么区别