簡體   English   中英

使用Guice為參數注釋編寫攔截器

[英]Writing interceptors for parameter annotations using Guice

我的問題的主要參考:


現在我的問題:

我正在編寫一個Java應用程序,它嚴重依賴於Google Guice來創建對象和處理依賴注入。 我試圖在執行某些帶注釋的方法之前使用攔截器來運行預處理代碼。 到目前為止,我已經成功地能夠使用Guice的指令對已經注釋的方法執行攔截器(使用MethodInterceptor接口)。 但是,我現在想編寫將在參數注釋上執行的攔截器。

這是一個示例場景。 首先,我創建自己的注釋。 例如::

@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) {
        ...
    }
}

最后,我需要創建一個吉斯注射器,並用它來創建一個instalce ExampleObject ,要不然我不能在這個項目中使用的方法攔截器。 我配置了Injector,以便將MyParameterAnnotationInterceptor綁定到@MyParameterAnnotation ,如下所示:

final MethodInterceptor interceptor = new MyParameterAnnotationInterceptor();
requestStaticInjection(MyParameterAnnotationInterceptor.class);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(MyParameterAnnotation.class), interceptor);

當我按照上面的步驟並執行對ExampleObject.foo()的調用時,遺憾的是,盡管參數被@MyParameterAnnotation標記,但攔截器仍未執行。 請注意,如果注釋放在方法級別 ,則這些類似的步驟將起作用。

這導致我得出兩個可能的結論:Guice不能支持將攔截器綁定到參數注釋,或者我正在做一些完全不正確的事情(也許我應該使用另一個AOP聯盟接口作為攔截器,比如FieldInterceptor ,但我非常懷疑因為Guice的AbstractModuleJavaDoc建議bindInterceptor()方法只能使用MethodInterceptor參數)。

盡管如此,所有人都非常感謝:)

匹配器用於方法注釋而不是方法參數注釋。

Guice沒有為方法參數注釋提供匹配器 - 您必須自己編寫一個或使用其他方案。 請注意,這是一個奇怪的用例 - 通常你可以逃脫

public class ExampleObject {
    @MyAnnotation
    public String foo(String param) {
        ...
    }
}

對於上面的例子,你有正確的Guice攔截器配置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM