我对AspectJ有意见。我在哪个方面将被编织之前向注释添加了参数,因此它不能工作。
注释接口:
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logged {
Event event();
System system();
}
我的观点是:
@Aspect
@Component
public class Aspect {
@Pointcut("@annotation(Logged) && args(event, system)")
public void invoke(Event event, System system) { }
@Around("invoke(event, system)")
public void aspectMethod (ProceedingJoinPoint, Event event, System system) {
System.out.println(event + " " + system);
}
}
事件和系统是枚举。
并在类似这样的方法之前添加了注释:
@Logged(event = Event.USER_LOGGED, system = System.WIN)
someTestingMethod();
只有当我将方面保留为:
@Aspect
@Component
public class Aspect {
@Pointcut("@annotation(Logged)")
public void invoke() { }
@Around("invoke()")
public void aspectMethod (ProceedingJoinPoint) {
System.out.println("Hey");
}
}
我不知道如何将参数传递给带有注释的方面。
发布于 2018-07-28 04:05:47
基本的解决方案是绑定注释:
@Aspect
class MyAspect {
@Pointcut("execution(* *(..)) && @annotation(l)")
public void invoke(Logged l) {}
@Around("invoke(l)")
public void aspectMethod (ProceedingJoinPoint pjp, Logged l) {
java.lang.System.out.println(l.event()+" "+l.system());
}
}
我使用execution()切入点只选择方法(所以我们想要带注释的方法),否则它会绑定注释的其他用户(在字段/类型等上)。正如有人指出的,args用于绑定方法参数,而不是注释。
https://stackoverflow.com/questions/51513527
复制相似问题