Didn’t you say you know Aop? Uh, this is it?

Author: Java journey

Original link: https://www.cnblogs.com/zhixie/p/13431251.html

Early in the morning, Xiao Wang hurried over to find me and said: Brother Zhou, I would like to ask about the logging function.

Because a certain project of the company needs to connect with other platforms, we need to provide them with a set of interfaces. Yesterday, I assigned Xiao Wang the work of recording interface logs.

The following is my main conversation with Xiao Wang.

Me: Tell me what's wrong?

Xiao Wang: I put the function of recording interface logs in each controller. Now it feels a bit cumbersome. Isn't it inappropriate for me to do this?

Me: Why do we need to record logs in each interface?

Xiao Wang: At first I used the interceptor, but such a request recorded two records.

Me: Why are there two?

Xiao Wang: Record a request data in preHandle and a response data in postHandle.

I:. . . Didn’t you say you know Aop?

Xiao Wang: The same is true for Aop. A request data is recorded in the front notification and a response data is recorded in the post notification.

Xiao Wang: This data is not the same as the previous operation log. In the past, it was only necessary to record an operation log in the pre-notification, but now there is a response, so the log can only be recorded in the controller.

Me: Do you know there is a surround notification? You talk about Aop on several types of notifications.

Xiao Wang: There are five kinds in total, namely:

  • Pre-notification: run before we execute the target method ( @Before )
  • Post notification: After our target method has finished running, regardless of whether there is an exception ( @After )
  • Return notification: run after our target method returns normally ( @AfterReturning )
  • Exception notification: run after an exception occurs in our target method ( @AfterThrowing )
  • Surround notification: The call of the target method is determined by the surrounding notification, that is, you can decide whether to call the target method, joinPoint.procced() is the code that executes the target method. The surrounding notification can control the return object ( @Around )

Next, let's demonstrate together how to use surround notification to solve Xiao Wang's problem.

Step 1 : Provide an interface to receive parameters and response interfaces

@RestController
public class TestController {
    @GetMapping("/getName")
    public String getName(HttpServletRequest request) throw Exception {

        String result = "Java旅途";
        String age = request.getParameter("age");
        if("18".equals(age)){
            result = "无法识别";
        }
        return result;
    }
}

Step 2 : Define the cut point

Execution() is a commonly used expression to define pointcuts. The syntax of execution() is as follows:

execution(修饰符  返回值  包.类.方法名(参数) throws异常)

among them:

Modifiers and throws exceptions can be omitted

Based on these explanations, we can use the execution() expression to describe the interface in the first step:

execution(String binzh.website.controller.TestController.GetName(HttpServletRequest))
  • *: match all items
  • ..: Match any number of method parameters
  • .. When it appears in the class name, it must be followed by *, which means all classes under the package and descendant package;

Now we optimize the above expression and define the aspect as the controller package and all methods of all packages under the controller

execution(* binzh.website.controller..*.*(..))

Step 3 : Record the log around the notification

@Around("execution(* binzh.website.controller..*.*(..))")
public Object around(ProceedingJoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String age = request.getParameter("age");
    Object proceed = "";
    try {
        proceed = joinPoint.proceed();
    } catch (Throwable e) {
        e.printStackTrace();
    }
    System.out.println("age==="+age);
    System.out.println("proceed ===="+proceed);
    return proceed;
}

The results are as follows:

age===19
proceed ====Java旅途

The reason why we can use surround notifications to deal with Xiao Wang's problem. One of the important reasons is that all the interfaces we provide are uniformly encrypted, and the last requested parameter is a fixed name . One more thing to note is that the return value type of the surrounding notification must be greater than or equal to the return value of the method, that is, adding your method returns a String type, and the surrounding notification cannot be written as a void type .

After seeing this, Xiao Wang suddenly realized that he was ready to go back and have a try. I hurriedly grabbed him.

Me: What if the interface is abnormal?

Xiao Wang: Then I can handle it in the exception notification.

Me: Do you think about it again?

Xiao Wang: It doesn't seem to work. The request parameters cannot be obtained in the exception notification.

Me: Is it possible to capture the processing in the surround notification?

At this time, seeing Xiao Wang's eyes glowing, he was surprised to say: The surround notification is too impressive, and it can complete the work of front notification, rear notification and abnormal notification!

Didn’t you say you know Aop?  Uh, this is it?

Guess you like

Origin blog.csdn.net/yunduo1/article/details/109097519