【问题标题】:How to access method annotation inside an advice using AspectJ?如何使用 AspectJ 访问通知中的方法注释?
【发布时间】:2018-11-05 19:25:41
【问题描述】:

我创建了一个切面来在执行某些方法之前使用 AspectJ 拦截它们,如下所示

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class SomeAspect {

    @Before("@annotation(com.test.package.MyCustomAnnotation)")
    public void validateSearchRestriction(final JoinPoint jp,
                           final MyCustomAnnotation annotation) {
        final String useCase = annotation.useCase();
    }
}

编写的自定义注解如下

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.stereotype.Component;

@Component
@Target(value = { ElementType.METHOD, ElementType.TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
public @interface SecurityRestricted {
    String useCase();
}

我面临的问题是我的方法中的第二个参数。 如果我尝试将我的方面中的注释作为第二个参数,应用程序将无法启动并出现以下错误。

bean 初始化失败;嵌套异常是 java.lang.IllegalArgumentException: error at ::0 切入点中的正式未绑定

原因:java.lang.IllegalArgumentException: ::0 切入点中的正式未绑定错误 在 org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression(PointcutParser.java:301) ~[aspectjweaver-1.8.0.jar:1.8.0]

如果我删除第二个参数,我的应用程序将正常启动。 这是获取方法注释的正确方法吗?

【问题讨论】:

  • 将您的切入点重写为@annotation(annotation),其中annotation 是您的方法参数的名称。这样,它应该绑定到您的方法签名中的参数。
  • 这行得通。万分感谢!干杯!
  • @M.Deinum 你认为值得写一个答案吗?如果是,请这样做。否则,我会这样做。这确实帮助了我。

标签: spring annotations aspectj interceptor


【解决方案1】:

如果要将变量从切入点绑定到方法,则需要从切入点引用变量。所以不要写@annotation(your.CustomAnnotation),你应该写@annotation(method-argument-name)

所以在你的情况下你的切入点看起来像

@Before(“@annotation(annotation)”)
public void validateSearchRestriction(JoinPoint jp, MyCustomAnnotation annotation) { ... }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多