2016-05-04 4 views
1

私はすべてのメソッドと特定の注釈のすべてのクラスに対してポイントカットを定義しました。私がしたいのは、すべてのメソッド呼び出しで注釈値を取得することです。ここでは、これまで私が持っているものであるアドバイスメソッドにポイントカットバインドアノテーションをどのように提供しますか?

@Aspect 
public class MyAspect { 

    @Pointcut("execution(* my.stuff..*(..))") 
    private void allMethods(){} 

    @Pointcut("within(@my.stuff.MyAnnotation*)") 
    private void myAnnotations(){} 

    @Pointcut("allMethods() && myAnnotations()") 
    private void myAnnotatedClassMethods(){} 

    @Before("myAnnotatedClassMethods()") 
    private void beforeMyAnnotatedClassMethods(){ 
     System.out.println("my annotated class method detected."); 
     // I'd like to be able to access my class level annotation's value here. 

    } 

} 

答えて

1

はい、あなたは春AOPがあなたのターゲットオブジェクトのクラスに注釈を付ける注釈の値を供給することができます。

binding forms documented in the specificationを使用し、@Pointcutの方法で引数を伝播する必要があります。

例えば

@Pointcut("execution(* my.stuff..*(..))") 
private void allMethods() { 
} 

@Pointcut("@within(myAnnotation)") 
private void myAnnotations(MyAnnotation myAnnotation) { 
} 

@Pointcut("allMethods() && myAnnotations(myAnnotation)") 
private void myAnnotatedClassMethods(MyAnnotation myAnnotation) { 
} 

@Before("myAnnotatedClassMethods(myAnnotation)") 
private void beforeMyAnnotatedClassMethods(MyAnnotation myAnnotation){ 
    System.out.println("my annotated class method detected: " + myAnnotation); 
} 

スプリングは、myAnnotationsポイントカットから出発して、メソッドパラメータと@withinで与えられた名前と一致し、注釈タイプを決定するためにそれを使用します。それはmyAnnotatedClassMethodsポイントカットを通してbeforeMyAnnotatedClassMethodsのアドバイスに伝えられます。

Spring AOPスタックは、@Beforeメソッドを呼び出す前に注釈値を検索し、それを引数として渡します。


代替は、あなたが上記の解決策が気に入らない場合は、単にあなたのアドバイスの方法でJoinPointパラメータを提供することです。これを使用してgetTargettargetインスタンスを解決し、その値を使用してクラス注釈を取得できます。たとえば、

@Before("myAnnotatedClassMethods()") 
private void beforeMyAnnotatedClassMethods(JoinPoint joinPoint) { 
    System.out.println("my annotated class method detected: " + joinPoint.getTarget().getClass().getAnnotation(MyAnnotation.class)); 
} 

ターゲットが他のプロキシでさらにラップされた場合の動作は不明です。注釈はプロキシクラスの背後に隠されているかもしれません。注意して使用してください。

関連する問題