Logging with Spring Boot AOP

Table of contents

introduce

1.1 What is AOP

1.2 AOP system and concept

Simple implementation of AOP

2.1 Create a new SpringBoot project without selecting dependencies

2.2 After setting up the local Maven configuration, add maven dependencies in the pom.xml file

2.3 Create a business class interface

2.4 Implement interface business in entity class 

2.5 Running results in unit tests

2.6 Create an aspect class

2.7 Run the test again

 Summarize


introduce

1.1 What is AOP

        AOP (Aspect Oriented Programming), oriented to aspect thinking, is one of Spring's three core ideas (two and two: IOC-inversion of control, DI-dependency injection).

        So why is AOP so important?

        In our programs, there are often some systematic requirements, such as permission verification, logging, statistics, etc. These codes will be scattered and interspersed in various business logics, such as the following schematic diagram:

31a4a7bec4ed3150224d48c74fd0f2bc.png

 

        It is obviously unacceptable to write as many duplicate checksum logging codes as there are business operations. Of course, using object-oriented thinking, we can extract these repeated codes and write them as public methods, which is as follows:

70f0688aa25cdbe8586e9cf3e665edf1.png

 

        In this way, the problems of code redundancy and maintainability are solved, but it is still a bit cumbersome to manually call these public methods in turn in each business method. Is there a better way? Yes, in order to solve this problem, aspect-oriented programming (AOP) came into being. AOP completely extracts non-business codes such as permission verification and log records, separates them from business codes, and finds nodes to cut into business codes:

239887065c6ce41b2abbed9e9b05901a.png

 

      AOP realizes the unified maintenance of program functions through pre-compilation and running dynamic agents. AOP is a continuation of OOP. It is a hot spot in software development and an important content in the Spring framework. It is a derivative of functional programming. AOP can be used to isolate various parts of the business logic, allowing developers to focus on the core business when writing business logic, thereby reducing the coupling between business logic modules and improving code reuse and development efficiency.  

        AOP uses a horizontal extraction mechanism to replace the repeated code construction of the vertical integration system. Using Aspect, the business logic only focuses on the business itself, and codes such as log management, transaction processing, performance statistics, exception handling, and access control are separated from the business logic code, so that the business logic code is not affected when these behaviors are changed.

1.2 AOP system and concept


Spring AOP and AspectJ

        The currently popular AOP frameworks are Spring AOP and AspectJ.

AOP-related terms


Simply understand, in fact, AOP has to do three types of things:

  • Where to cut in, that is, in which business codes are non-business operations such as permission verification performed.

  • When to cut in, is it before or after the execution of the business code.

  • What to do after logging in, such as permission verification, logging, etc.

Therefore, the AOP system can be sorted out as the following figure:

b2d561096aca93133f405e98db521bf7.png

 

Simple implementation of AOP

        Let's demonstrate the primary application of AOP through a simple case:

2.1 Create a new SpringBoot project without selecting dependencies

2.2 After setting up the local Maven configuration, add maven dependencies in the pom.xml file

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

2.3 Create a business class interface

         As shown in the figure, establish the corresponding software package and interface, and create a method in the interface:

2.4 Implement interface business in entity class 

        Note that you must add the Service annotation 

2.5 Running results in unit tests

2.6 Create an aspect class

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.StringJoiner;

@Component
@Aspect
public class LogAspect {
    @Before("execution(* com.example.aopdemo.service..*.*(..))")
    public void sysLog(JoinPoint jp){
        StringJoiner log = new StringJoiner("|","{","}");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");
        log.add(formatter.format(LocalDateTime.now()));

        //当前执行的业务方法名称
        String methodName = jp.getSignature().getName();
        log.add(methodName);

        //方法的参数
        Object[] args = jp.getArgs();
        for(Object arg:args){
            log.add(arg == null ? "-" : arg.toString() );
        }

        System.out.println("AOP日志启动!" + log);
    }

2.7 Run the test again

        Run it again and find that our log has been added, and the original code has not been changed. This is the silkiness of AOP.

 Summarize

        AOP uses a horizontal extraction mechanism to replace the repeated code construction of the vertical integration system. Using Aspect, the business logic only focuses on the business itself, and codes such as log management, transaction processing, performance statistics, exception handling, and access control are separated from the business logic code, so that the business logic code is not affected when these behaviors are changed. It is really a necessary artifact for development, this article is over, I hope everyone can gain something~

Guess you like

Origin blog.csdn.net/qq_51294997/article/details/132003391