2017-10-04 13 views
1

注釈付きの引数の値をSpring AOPに認識させる方法はありますか? (アスペクトに渡された引数の順番での保証はないので、アスペクトを処理するために使用する必要があるパラメータをマークするために注釈を使用したいと考えています)。メソッドとパラメータアノテーションを使用するSpring AOP

役に立った

@Target({ElementType.METHOD}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Wrappable { 
} 


@Target({ElementType.PARAMETER}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Key { 
} 

@Wrappable 
public void doSomething(Object a, @Key Object b) { 
    // something 
} 

@Aspect 
@Component 
public class MyAspect { 
    @After("@annotation(trigger)" /* what can be done to get the value of the parameter that has been annotated with @Key */) 
    public void trigger(JoinPoint joinPoint, Trigger trigger) { } 

答えて

1

以下は、タグ付きメソッドを処理する必要のあるアスペクトクラスの例です。@Wrappable注釈。 ラッパーメソッドが呼び出されると、メソッドパラメータを反復処理して、@注釈でタグ付けされたパラメータがあるかどうかを調べることができます。 keyParamsリストには、@アノテーションでタグ付けされたパラメータが含まれています。

@Aspect 
@Component 
public class WrappableAspect { 

    @After("@annotation(annotation) || @within(annotation)") 
    public void wrapper(
      final JoinPoint pointcut, 
      final Wrappable annotation) { 
     Wrappable anno = annotation; 
     List<Parameter> keyParams = new ArrayList<>(); 

     if (annotation == null) { 
      if (pointcut.getSignature() instanceof MethodSignature) { 
       MethodSignature signature = 
         (MethodSignature) pointcut.getSignature(); 
       Method method = signature.getMethod(); 
       anno = method.getAnnotation(Wrappable.class); 

       Parameter[] params = method.getParameters(); 
       for (Parameter param : params) { 
        try { 
         Annotation keyAnno = param.getAnnotation(Key.class); 
         keyParams.add(param); 
        } catch (Exception e) { 
         //do nothing 
        } 
       } 
      } 
     } 
    } 
} 
0

注釈が実際のパラメータではなく、そこにあなただけの実引数を参照することができますので、我々は、我々は法の注釈のためにそれをやっているようにAOPへの引数としてパラメータの注釈値を取得することはできません。

args(@Key b) 

この注釈は、@Key注釈の値ではなくObject(b)の値を提供します。

我々は、パラメータの注釈

MethodSignature methodSig = (MethodSignature) joinpoint.getSignature(); Annotation[][] annotations = methodSig.getMethod().getParameterAnnotations(); if (annotations != null) { for (Annotation[] annotArr : annotations) { for (Annotation annot : annotArr) { if (annot instanceof KeyAnnotation) { System.out.println(((KeyAnnotation) annot).value()); } } } }の値を取得するには、この方法で行うことができます。

関連する問題