@AspectJ切入点覆盖带有注释的接口方法的方法

Han*_*örr 17 java aop aspectj pointcuts pointcut

如何编写适用于覆盖带注释的接口方法的方法执行的aspectj切入点?例如:

interface A {
  @MyAnnotation void method();
}
class B implements A {
  void method();
}
Run Code Online (Sandbox Code Playgroud)

切入点execution(@MyAnnotation * *.*(..))仅在B.method()带有注释本身时匹配.还有另一种方法吗?

Guv*_*ven 12

正如尼古拉斯指出的那样,这在AspectJ中是不可能的.这里有更多证据证明为什么它不可能(取自http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-pointcuts-and-advice.html部分注释继承和切入点匹配):

根据Java 5规范,非类型注释不会被继承,类型注释只有在具有@Inherited元注释的情况下才会被继承.对c2.aMethod的调用(在您的示例中将是b.method())不匹配,因为修饰符的连接点匹配(可见性修饰符,注释和throws子句)基于连接点的主题(实际被调用的方法).

遇到同样的问题,我写了一个小方法/库,可以让你为这些方法编写切入点.以下是它如何适用于您的示例:

myAnnotationIsExecuted(): execution(public * *.*(..)) && 
             if(implementsAnnotation("@MyAnnotation()", thisJoinPoint));
Run Code Online (Sandbox Code Playgroud)

要么

myAnnotationIsExecuted(): execution(public * A+.*(..)) &&
             if(implementsAnnotation("@MyAnnotation()", thisJoinPoint));
Run Code Online (Sandbox Code Playgroud)

该方法implementsAnnotation(String,JoinPoint)来自图书馆; 检查实现的方法是否包含指定注释的基本方法.

有关方法/库的更多信息,请参见此处.