Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring AOP change value of methods argument on around advice

Is it possible to change method argument value on basis of some check before executing using Spring AOP

My method

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

Advice method

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

Please suggest me the way to set the method argument value as there is no setter options for the argument.

like image 331
Ashish Aggarwal Avatar asked Sep 03 '15 07:09

Ashish Aggarwal


People also ask

Which AOP advice can access and modify argument of a JoinPoint?

You can use Spring AOP, create point cut using @Around . Then you can use the below code to change the arguments of the method, based on the condition. int index = 0; Object[] modifiedArgs = proceedingJoinPoint.

Which aspects can change the original argument value of the target method and also return value of the method?

This tutorial provided introduction to Spring AOP Around Advice, which is the most powerful advice. Around advice can prevent the actual method execution and return a response on methods behalf. It can also change the argument values to the target method.

What will after advice do in Spring AOP?

After advice is used in Aspect-Oriented Programming to achieve the cross-cutting. It is an advice type which ensures that an advice runs after the method execution. We use @After annotation to implement the after advice.

Which advice allows you to access arguments of JoinPoint in advice?

We use @AfterThrowing annotation for this type of advice. Around Advice: This is the most important and powerful advice. This advice surrounds the join point method and we can also choose whether to execute the join point method or not.


1 Answers

Yes that's possible. You need a ProceedingJoinPoint and instead of:

methodInvocation.proceed();

you can then call proceed with the new arguments, for example:

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

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

like image 87
reto Avatar answered Sep 21 '22 13:09

reto