【问题标题】:aspectj not intercepting methods with annotationaspectj 不拦截带有注释的方法
【发布时间】:2018-12-05 11:53:17
【问题描述】:

我正在尝试让 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 *)")

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

【问题讨论】:

    标签: java aspectj


    【解决方案1】:

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

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

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

    【讨论】:

    • 好的,我在文档站点上也看到了这种方法,但是为什么我有其他方面的工作呢?
    • @Walter 哪一个?可以加吗?
    • 我将它添加到帖子的末尾 - 我想我应该更改它以匹配您提供的示例。
    【解决方案2】:

    当你使用自定义注解时,你应该使用@annotation 而不是 inside:

    @Aspect
        public class InterceptMeAspect {
          @Around("execution(* *(..)) && @annotation(com.or.org.package.InterceptMe)")
    

    【讨论】:

    • @com.or.org.package.InterceptMe需要替换成com.or.org.package.InterceptMe
    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多