AOP is a language-independent programming paradigm. In project business logic, common modules are separated and processed in a horizontal way, which is often used for logging, permission control, exception handling and other services.

Quick navigation

  • Introducing AOP dependencies
  • AOP often uses annotation parsing
  • Implement log splitting function
    • @PointcutAdd pointcuts
    • @BeforePre notice
    • @AfterThe rear notice
    • @AroundSurrounding the notification
    • @AfterReturningNotification of return
    • @AfterReturningAbnormal notice
  • Snippets of pseudocode read the order of execution
  • The normal and abnormal conditions were tested separately

Programming paradigms fall into the following categories

  • Aspect Oriented Programming (AOP) is Aspect Oriented Programming
  • Object Oriented Programming (OOP)
  • POP (Procedure Oriented Programming) Procedure oriented programming
  • FP (Functional Programming) Functional oriented Programming

Introducing AOP dependencies

MySQL Chapter2-1 MySQL Chapter2-1 MySQL Chapter2-1 MySQL Chapter2-1 MySQL Chapter2-1

The project root pom. XML adds dependencies on Spring-boot-starter-AOP

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Copy the code

Aop annotations

  • @Aspect: aspect, which consists of both advice and pointcuts. This annotation annotation is represented as an aspect on the class.
  • @JoinpointJoin points, classes or methods that are intercepted by AOP, as described in the pre-notification@JoinpointGets the class name, method, request parameters.
  • Advice: Types of notification
    • @Before: pre-notification, at a pointcut@PointcutPrevious notice
    • @After: post-notification, at a pointcut@PointcutSubsequent notifications whether successful or abnormal.
    • @AfterReturning: notifies the method when it returns. After the method returns, it can process the returned data.
    • @Around: surrounds the notification, executed before and after a method is called.
    • @AfterThrowing: Throws an exception notification, which is executed when the program fails to run an exception.
  • @PointcutEntry point where to start Such as starting from a package or a class under a package, etc.

Implement log splitting function

Create the httpAspect. Java class under the directory aspect, after receiving the request, record the relevant parameter log information of the request, print the response information after successfully completing the request, and print the error log information of the request processing error.

httpAspect.java

package com.angelo.aspect;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class HttpAspect {
    // Prints the log module
    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    // The following will introduce...
Copy the code

Add pointcuts

Where do you define entry points that encapsulate a common method for reuse

httpAspect.java

    /** * define a public method for intercepting all methods under UserController * intercepting any arguments in the userList method under UserController (.. Intercept any argument@Before("execution(public * com.angelo.controller.UserController.userList(..) ) * / ")
    @Pointcut("execution(public * com.angelo.controller.UserController.*(..) )")
    public void log(a) {}Copy the code

Pre notice

Intercept a piece of business logic before the method to get some information about the request, which uses Gson to handle the object to JSON output

httpAspect.java

@Before("log()")
public void doBefore(JoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    Map params = new HashMap();
    params.put("url", request.getRequestURL()); // Get the requested URL
    params.put("method", request.getMethod()); // How to get the request
    params.put("ip", request.getRemoteAddr()); // Get the requested IP address
    params.put("className", joinPoint.getSignature().getDeclaringTypeName()); // Get the class name
    params.put("classMethod", joinPoint.getSignature().getName()); // Get the class method
    params.put("args", joinPoint.getArgs()); // Request parameters

    // Outputs a formatted JSON string
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    logger.info("REQUEST: {}", gson.toJson(params));
}
Copy the code

The rear notice

Intercepting a piece of business logic after a method

httpAspect.java

@After("log()")
public void doAfter(a) {
    logger.info("doAfter");
}
Copy the code

Surrounding the notification

Around before and after the notice is the method of a logic operation, can modify the return value of the target method, the first parameter is the org. Aspectj. Lang. ProceedingJoinPoint type, note that there must carry out the target method calls proceed () get the value to return, or it will cause the null pointer exception. Error returns can also be caught in the surround notification.

httpAspect.java

@Around("log()")
public Object doAround(ProceedingJoinPoint point) {
    try {
        Object o =  point.proceed();
        System.out.println("Method surrounds proceed, resulting in :" + o);
        logger.info("doAround1");

        return o;
    } catch (Throwable e) {
        // e.printStackTrace();
        logger.info("doAround2");

        return null; }}Copy the code

Notification of return

A return notification after the pointcut completes, at which point no exception notification is thrown unless the business logic of the return notification fails.

httpAspect.java

    /** * Gets the response return value *@param object
     */
    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        // logger.info("RESPONSE: {}", object); It prints out an object, and to print out what it is you have to add toString() to the definition model

        logger.info("RESPONSE: {}", object.toString());
    }
Copy the code

Abnormal notice

Notification after an exception is thrown, notification @afterRETURNING will not be executed.

httpAspect.java

@AfterThrowing(pointcut = "log()")
public void doAfterThrowing(a) {
    logger.error("doAfterThrowing: {}"."Abnormal condition!);
}
Copy the code

Snippets of pseudocode read the order of execution

try {
    // @before Notification Before execution

    // Execute the target method

    // @around Execute finall on success, catch on failure
} finally {
    // @after perform post-notification

    // @afterRETURNING Notification
} catch(e) {
    // @afterthrowing throws exception notifications
}
Copy the code

Test normal abnormal two cases

Test before the controller/UserController. Java file userList method increased the exception argument

    /** * Query the user list *@return* /
    @RequestMapping(value = "/user/list/{exception}")
    public List<User> userList(@PathVariable("exception") Boolean exception) {
        if (exception) {
            throw new Error("Test throw exception!");
        }

        return userRepository.findAll();
    }
Copy the code
  • Test normal condition

The curl 127.0.0.1:8080 / user/list/false

The normal return value is as follows:

  • Test exception

The curl 127.0.0.1:8080 / user/list/true

The return value in the abnormal case is as follows:

The above two case tests show that the surround notification can be executed in both normal and abnormal cases.

Github see the full example chapter3-1 for this article

Author: you may link: www.imooc.com/article/259… Github: Spring Boot