It’s a bit of a weird scenario, but there’s some generality to the AOP part.

As a legacy system, we want to tinker with all the action methods and rewrite the input parameters in some cases, such as userId, to the anonymous account we have pre-established if we find that the requested userId is not correct.

If it is one or two methods are ok, directly change on the line, but there are more than ten of the time, not from the way to think there is no lazy, the answer is AOP.

For all actions that need rewriting, we can do an Around block so that we can manipulate the input parameter before the method is executed:

@Aspect
@Component
public class AroundAdvice {

    @Around("execution(* com.mmliu.controller.user.*.*(..) ) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object processTx(ProceedingJoinPoint jp) throws java.lang.Throwable {
        System.out.println("Before executing the target method...");

        MethodSignature methodSignature = (MethodSignature) jp.getSignature();
        String[] paramNames = methodSignature.getParameterNames();

        Update the value of userId if it contains userId and needs to be updated
        Object[] args = jp.getArgs();
        for(int i = 0; i < paramNames.length; i++){
            if("userId".equals(paramNames[i])){
                Object userIdObj = args[i];
                long userId = Long.valueOf(userIdObj.toString());

                if(needChangeId(userId) <= 0){
                    userId = 1000000L; } args[i] = userId; }}// Execute the target method and save the return value of the target method after execution
        Object rvt = jp.proceed(args);

        System.out.println("After executing the target method");

        returnrvt; }}Copy the code

Proceed (args) Object RVT = jp.proceed(args) The value args of the Action method has been updated.

Thus, with AOP, we were able to change the program’s logic with little or no intrusion into the original code, and we were able to successfully steal the slack by not modifying it method by method.