Spring AOP 根据周围建议更改方法参数的值

Spring AOP change value of methods argument on around advice

是否可以在使用 Spring AOP

执行之前根据某些检查更改方法参数值

我的方法

public String doSomething(final String someText, final boolean doTask) {
    // Some Content
    return "Some Text";
}

咨询方法

public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
    String methodName = methodInvocation.getMethod().getName();

    Object[] arguments = methodInvocation.getArguments();
    if (arguments.length >= 2) {
        if (arguments[0] instanceof String) {
            String content = (String) arguments[0];
            if(content.equalsIgnoreCase("A")) {
                // Set my second argument as false
            } else {
                // Set my second argument as true
            }
        }
    }
    return methodInvocation.proceed();
}

请建议我设置方法参数值的方法,因为参数没有 setter 个选项。

是的,这是可能的。您需要 ProceedingJoinPoint 而不是:

methodInvocation.proceed();

然后您可以使用新参数调用 proceed,例如:

methodInvocation.proceed(new Object[] {content, false});

http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html#aop-ataspectj-advice-proceeding-with-the-call

我使用 MethodInvocation

得到了答案
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
    String methodName = methodInvocation.getMethod().getName();

    Object[] arguments = methodInvocation.getArguments();
    if (arguments.length >= 2) {
        if (arguments[0] instanceof String) {
            String content = (String) arguments[0];
            if(content.equalsIgnoreCase("A")) {
                if (methodInvocation instanceof ReflectiveMethodInvocation) {
                    ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
                    arguments[1] = false;
                    invocation.setArguments(arguments);
                }
            } else {
                if (methodInvocation instanceof ReflectiveMethodInvocation) {
                    ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
                    arguments[1] = true;
                    invocation.setArguments(arguments);
                }
            }
        }
    }
    return methodInvocation.proceed();
}

您可以使用 Spring AOP,使用 @Around 创建切点。 然后您可以使用以下代码根据条件更改方法的参数。

int index = 0;
Object[] modifiedArgs = proceedingJoinPoint.getArgs();

for (Object arg : proceedingJoinPoint.getArgs()) {
    if (arg instanceof User) {    // Check on what basis argument have to be modified.
        modifiedArgs[index]=user;
       }
    index++;
}
return proceedingJoinPoint.proceed(modifiedArgs);  //Continue with the method with modified arguments.