Spring AOP更改了关于建议

时间:2015-09-03 07:39:41

标签: java spring spring-aop

在使用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选项。

3 个答案:

答案 0 :(得分:8)

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

methodInvocation.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

答案 1 :(得分:3)

我使用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();
}

答案 2 :(得分:1)

您可以使用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.