Spring AOP 使用方法和参数注释

shi*_*njw 5 java spring annotations spring-aop

有没有办法让 Spring AOP 识别已注释的参数的值?(无法保证传递到切面的参数的顺序,因此我希望使用注释来标记需要用于处理切面的参数)

任何替代方法也会非常有帮助。

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Wrappable {
}


@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Key {
}

@Wrappable
public void doSomething(Object a, @Key Object b) {
    // something
}

@Aspect
@Component
public class MyAspect {
    @After("@annotation(trigger)" /* what can be done to get the value of the parameter that has been annotated with @Key */)
    public void trigger(JoinPoint joinPoint, Trigger trigger) { }
Run Code Online (Sandbox Code Playgroud)

Ind*_*sak 5

下面是一个切面类的示例,它应该处理用@Wrappable注释标记的方法。调用包装方法后,您可以迭代方法参数以查找是否有任何参数带有@Key注释。keyParams列表包含用@Key注释标记的任何参数

@Aspect
@Component
public class WrappableAspect {

    @After("@annotation(annotation) || @within(annotation)")
    public void wrapper(
            final JoinPoint pointcut,
            final Wrappable annotation) {
        Wrappable anno = annotation;
        List<Parameter> keyParams = new ArrayList<>();

        if (annotation == null) {
            if (pointcut.getSignature() instanceof MethodSignature) {
                MethodSignature signature =
                        (MethodSignature) pointcut.getSignature();
                Method method = signature.getMethod();
                anno = method.getAnnotation(Wrappable.class);

                Parameter[] params = method.getParameters();
                for (Parameter param : params) {
                    try {
                        Annotation keyAnno = param.getAnnotation(Key.class);
                        keyParams.add(param);
                    } catch (Exception e) {
                        //do nothing
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)