我已经定义了一个元注解和一些用元注解的具体注解。我目前正在尝试实现一个方面,该方面将根据元注释编织用这些具体注释注释的方法。我能够使用这个切入点来实现建议调用。
"execution(@(@my.meta.Annotation *) * *(..))"
但是,我想使用参数绑定,因为元注释定义了一个我感兴趣的值的字段。不幸的是,我找不到正确的表达式来实现它。
使用嵌套注释切入点时是否可以使用参数绑定,或者我是否需要从
JoinPoint
获取注释?
通过
@annotation()
的注释绑定,@within()
需要一个精确的类,但你想要一个通用的解决方案。因此,您确实需要通过反射从方法中获取注释,即您需要走这条路线:
joinpoint → signature → method → annotation → meta annotation
package de.scrum_master.stackoverflow.q75834894.app;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
@Retention(RUNTIME)
public @interface Meta {
String id();
}
package de.scrum_master.stackoverflow.q75834894.app;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
@Retention(RUNTIME)
@Meta(id = "indirect")
public @interface Marker {}
package de.scrum_master.stackoverflow.q75834894.app;
public class Application {
public static void main(String[] args) {
Application application = new Application();
application.notAnnotated();
application.metaAnnotated();
application.markerAnnotated();
}
public void notAnnotated() {}
@Meta(id = "direct") public void metaAnnotated() {}
@Marker public void markerAnnotated() {}
}
package de.scrum_master.stackoverflow.q75834894.aspect;
import java.lang.annotation.Annotation;
import org.aspectj.lang.reflect.MethodSignature;
import de.scrum_master.stackoverflow.q75834894.app.Meta;
public aspect MyAspect {
before(Meta meta) : @annotation(meta) && execution(* *(..)) {
System.out.println(thisJoinPoint);
System.out.println(" " + meta.id());
}
before() : execution(@(@de.scrum_master.stackoverflow.q75834894.app.Meta *) * *(..)) {
System.out.println(thisJoinPoint);
for (Annotation annotation : ((MethodSignature) thisJoinPoint.getSignature()).getMethod().getAnnotations()) {
Meta meta = annotation.annotationType().getAnnotation(Meta.class);
if (meta != null)
System.out.println(" " + meta.id());
}
}
}
我想您知道如何将本机语法方面转换为基于注释的方面语法,如果您愿意的话。
控制台日志:
execution(void de.scrum_master.stackoverflow.q75834894.app.Application.metaAnnotated())
direct
execution(void de.scrum_master.stackoverflow.q75834894.app.Application.markerAnnotated())
indirect