modify method arguments using spring aspect

@Before

For logging kinds of stuff, we usually use the “@Before”

 

@Aspect
public class LoggingAspect {

    @Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
    public void logBefore(JoinPoint joinPoint) {

        System.out.println("logBefore() is running!");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("******");
        
        //get args
        Object[] args = joinPoint.getArgs();
    }

}

A before advice gets a copy of the argument array, but it can’t modify the original arguments. 

 

 

@Around

So in order to modify , we need to use “@Around” with which you can pass the args to the execution!

 

@Around("execution(* de.foo.entity.*.set*(..)) && args(java.lang.String)")
public void checkAroundSetter(final ProceedingJoinPoint pjp)
    throws Throwable {
    LOGGER.debug(pjp.getSignature().toLongString());
    Object[] args = pjp.getArgs();
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof String && ((String) args[i]).isEmpty()) {
            args[i] = null;
        }
    }
    pjp.proceed(args);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s