Spring AOP更改方法参数的值,围绕建议

Ash*_*wal 12 java spring spring-aop

在使用Spring AOP执行之前,是否可以在某些检查的基础上更改方法参数值

我的方法

public String doSomething(final String someText, final boolean doTask) {
    // Some Content
    return "Some Text";
}
Run Code Online (Sandbox Code Playgroud)

建议方法

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();
}
Run Code Online (Sandbox Code Playgroud)

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

ret*_*eto 8

是的,这是可能的.你需要一个ProceedingJoinPoint而不是:

methodInvocation.proceed();
Run Code Online (Sandbox Code Playgroud)

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

methodInvocation.proceed(new Object[] {content, false});
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意:重构过程中很容易跳过这些内容.如果你没有漂亮的测试套件,它会受到伤害. (2认同)

Ash*_*wal 5

我得到了我的答案 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();
}
Run Code Online (Sandbox Code Playgroud)


Sub*_*lil 5

您可以使用 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.
Run Code Online (Sandbox Code Playgroud)