私の質問の主な参考資料:
- Google Guiceのメソッドインターセプターの作成:http ://code.google.com/p/google-guice/wiki/AOP
- MethodInterceptorインターフェース用の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
今私の質問:
オブジェクトの作成と依存性注入の処理をGoogleGuiceに大きく依存するJavaアプリケーションを作成しています。特定の注釈付きメソッドが実行される前に、インターセプターを使用して前処理コードを実行しようとしています。MethodInterceptor
これまでのところ、 Guiceの指示を使用して、注釈が付けられたメソッドに対して(インターフェイスを使用して)インターセプターを正常に実行することができました。ただし、ここで、パラメーターアノテーションで実行されるインターセプターを作成します。
シナリオの例を次に示します。まず、独自の注釈を作成します。例えば::
@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インジェクターを作成し、それを使用してのインストールを作成する必要がありますExampleObject
。そうしないと、このプロジェクトでメソッドインターセプターを使用できません。MyParameterAnnotationInterceptor
次のように、がにバインドされるようにインジェクターを構成します@MyParameterAnnotation
。
final MethodInterceptor interceptor = new MyParameterAnnotationInterceptor();
requestStaticInjection(MyParameterAnnotationInterceptor.class);
bindInterceptor(Matchers.any(), Matchers.annotatedWith(MyParameterAnnotation.class), interceptor);
上記の手順に従ってへの呼び出しを実行するとExampleObject.foo()
、残念ながら、パラメーターが。でマークされているにもかかわらず、インターセプターは実行されません@MyParameterAnnotation
。代わりにアノテーションがメソッドレベルで配置された場合、これらの同様の手順が機能することに注意してください。
これにより、2つの考えられる結論が導き出されます。Guiceがインターセプターをパラメーターアノテーションにバインドすることをサポートできないか、完全に間違った処理を行っています(おそらく、FieldInterceptorなどのインターセプターに別のAOP Allianceインターフェイスを使用する必要がありますが、非常に疑わしいです。これは、JavaDoc for GuiceのAbstractModuleが、メソッドがパラメーターbindInterceptor()
のみを使用できることを示唆しているためです)。MethodInterceptor
それにもかかわらず、すべてが私たちを大いに感謝するのに役立ちます:)