首页 > 解决方案 > aspectj 不拦截带有注释的方法

问题描述

我试图让 aspectj 拦截带注释的方法:

@Aspect
    public class InterceptMeAspect {
      @Around("execution(* *(..)) && within(@InterceptMe *)")
      public Object doIntercept(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("intercepted:");
        return proceedingJoinPoint.proceed();
      }
    }

    public class InterceptedExample {
        @InterceptMe
        public void doSomething(){

        }
    }

为简洁起见,我删除了 !within(InterceptMeAspect) ,但无论如何它并没有拦截太多。如果我删除注释约束(在(@InterceptMe *)内),它可以工作,但会拦截所有内容并造成大问题。

输出字节码似乎具有完整的注释,因此我希望注释标准匹配。我正在做或尝试做编译时编织。这很重要,因为我有另一个方面可以使用上述相同的方法。我怀疑这方面有问题,但最终的字节码不应该有注释,对吧?

编辑:这是另一方面的代码:

@Around(
      "execution(protected * *(..)) && !within(com.walterjwhite.logging..*) && !call(*.new(..)) && within(@ContextualLoggable *) && !within(@NonLoggable *)")

我有一个通用的日志记录方面和一个特殊的上下文日志记录方面。我猜这也写错了,应该遵循上面的格式。

标签: javaaspectj

解决方案


而不是@Around("execution(* *(..)) && within(@InterceptMe *)"). 它应该是@Around("execution(* *(..)) && @annotation(your.package.InterceptMe )")

或者,如果您需要从注释中访问某些属性:

@Around("execution(* *(..)) && @annotation(interceptMeVar)")
public Object doIntercept(ProceedingJoinPoint proceedingJoinPoint,InterceptMe interceptMeVar)

推荐阅读