如何获取带注释的方法参数及其注释

2dy*_*2dy 6 java aop spring aspectj

在我的应用程序中,我有一些带有注释的参数的方法。现在我想编写使用注释属性信息对注释参数进行一些预处理的 Aspect。例如方法:

public void doStuff(Object arg1, @SomeAnnotation CustomObject arg1, Object arg2){...}
Run Code Online (Sandbox Code Playgroud)

方面:

@Before(...)
public void doPreprocessing(SomeAnnotation annotation, CustomObject customObject){...}
Run Code Online (Sandbox Code Playgroud)

@Before 中应该写什么?

编辑:

谢谢大家。有我的解决方案:

@Before("execution(public * *(.., @SomeAnnotation (*), ..))")
public void checkRequiredRequestBody(JoinPoint joinPoint) {
    MethodSignature methodSig = (MethodSignature) joinPoint.getSignature();
    Annotation[][] annotations = methodSig.getMethod().getParameterAnnotations();
    Object[] args = joinPoint.getArgs();

    for (int i = 0; i < args.length; i++) {
        for (Annotation annotation : annotations[i]) {
            if (SomeAnnotation.class.isInstance(annotation)) {
                //... preprocessing
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

And*_*fan 5

你会这样做:

@Before("execution(* com.foo.bar.*.doStuff(..)) && args(arg1, arg2)")
    public void logSomething(JoinPoint jp, CustomObject arg1, Object arg2) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        Class<?> clazz = methodSignature.getDeclaringType();
        Method method = clazz.getDeclaredMethod(methodSignature.getName(), methodSignature.getParameterTypes());
        SomeAnnotation argumentAnnotation;
        for (Annotation ann : method.getParameterAnnotations()[0]) {
            if(SomeAnnotation.class.isInstance(ann)) {
                argumentAnnotation = (SomeAnnotation) ann;
                System.out.println(argumentAnnotation.value());
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是参数类型自定义注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SomeAnnotation {
    String value();
}
Run Code Online (Sandbox Code Playgroud)

以及要拦截的方法:

public void doStuff(@SomeAnnotation("xyz") CustomObject arg1, Object arg2) {
        System.out.println("do Stuff!");
    }
Run Code Online (Sandbox Code Playgroud)

你不能这样做

@Before(...)
public void doPreprocessing(SomeAnnotation annotation, CustomObject customObject){...}
Run Code Online (Sandbox Code Playgroud)

因为注释不是参数,在那里你只能引用参数。您可以按照自己的方式使用 using @args(annot),但这仅匹配放置在参数类型本身上的注释,而不是实际参数前面的注释。@args(annot)适用于这样的情况:

@SomeAnnotation
public class CustomObject {

}
Run Code Online (Sandbox Code Playgroud)