Spring AOP, Spring Boot unified function processing and transaction learning


foreword

Spring AOP is a framework that implements the idea of ​​aspect-oriented programming, which can realize the unified processing of functions with unified functions and many places of use.


1. Spring AOP

1. What is Spring AOP?

AOP (Aspect Oriented Programming): Aspect Oriented Programming is a kind of thinking, which is a centralized processing of a certain type of thing. Spring AOP is a framework and a concrete realization of AOP ideas. Similar to the relationship between IoC and DI.
Main learning:
1. How AOP is composed.
2. The use of Spring AOP.
3. The realization principle of Spring AOP.

2. AOP composition

(1) Aspect

Aspects consist of cut points and join points. In the program, it is a class that deals with specific problems in a certain aspect. The class contains many methods, and these methods are point cuts and notifications.

(2) Pointcut

Rules (configuration) for active blocking.

(3) Advice

The aspect work, the specific action triggered by the intercepted request in the program, is the specific business code implemented in the notification.
(1) Pre-notification: The method executed before executing the target method is called pre-notification.
(2) Post-notification: The method executed after the target method is executed is called post-notification.
(3) Exception notification: the execution notification when an exception occurs when the target method is executed.
(4) Return notification: The notification executed when the target method executes the return data (return).
(5) Surround notification: A method that can be executed within the execution cycle of the target method (before execution, during execution, and after execution) is called surround notification.

(4) Joint Point

A point during application execution that can be inserted into an aspect. This point can be when a method is called, when an exception is thrown, or even when a field is modified. Aspect code can use these points to be inserted into the normal flow of the application and add new behavior.
All points where an AOP rule might be triggered (all requests).

3. Use of Spring AOP

1. Add Spring AOP dependencies;
when creating a Spring Boot project, there is no Spring AOP framework to choose from. After creating the project, add Spring AOP dependencies in pom.xml.
insert image description here
insert image description here

		<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-aop -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
			<version>2.7.9</version>
		</dependency>

2. Define the aspect (create the aspect class);

insert image description here

3. Define the cut point (configure interception rules);
insert image description here

4. Define the implementation of the notification.
insert image description here
Surround notifications:

    //环绕通知
    @Around("pointcut()")
    public Object aroundAdvice(ProceedingJoinPoint jointPoint) throws Throwable {
    
    
        System.out.println("进入环绕通知了~");
        Object obj = null;
        //执行目标方法
        obj = jointPoint.proceed();
        System.out.println("退出环绕通知了~");
        return obj;
    }

4. Spring AOP implementation principle

Spring AOP is built on the basis of dynamic proxy, so Spring's support for AOP is limited to method-level interception.
Spring's aspect wraps the proxy class implementation of the target object, and the proxy class handles method calls, executes additional aspect logic, and calls additional methods.

2. Spring Boot unified function processing

1. Use interceptors to realize unified validation of user login permissions

(1) Difficulties in implementing unified interception with native Spring AOP:
a. It is very difficult to define interception rules (expressions);
b. It is difficult to obtain HttpSession in the aspect class.
(2) Implement a common interceptor
Key steps:
a. Implement the HandlerInterceptor interface;
b. Rewrite the preHeadler method and write your own business code in the method.

public class LoginInterceptor implements HandlerInterceptor {
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
    
        //用户登录业务逻辑
        HttpSession session = request.getSession(false);
        if (session!=null && session.getAttribute("userinfo") !=null) {
    
    
            //说明用户以及登录
            return true;
        }
        //可以调整到登录页面 或者 返回一个 401/403 没有权限码
        response.sendRedirect("/login.html");
        return false;
    }
}

(3) Add the interceptor to the configuration file and set the interception rules

@Configuration
public class AppConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**") //拦截所有请求
                .excludePathPatterns("/user/login") //排除URL地址(不拦截的URL地址)
                .excludePathPatterns("/user/reg")
                .excludePathPatterns("/**/*.html");
    }
}

Configure a unified prefix for the current project:
(1) Set it in the system configuration file;

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
    
    
        configurer.addPathPrefix("/zhangsan",c->true);
    }

(2) Configure in application.properties/.yml.

2. Unified exception return

Unified encapsulation of exceptions:
(1) Create a class and mark @ControllerAdvice on the class;

(2) Add the method @ExceptionHandler to subscribe to exceptions.

@ControllerAdvice
public class MyExHandler {
    
    

    //拦截所有的空指针异常,并统一处理
    @ExceptionHandler(NullPointerException.class)
    public HashMap<String,Object> nullException(NullPointerException e) {
    
    
        HashMap<String,Object> result = new HashMap<>();
        result.put("code","-1");
        result.put("msg","空指针异常:"+e.getMessage());
        result.put("data",null);
        return result;
    }
}

3. Return of unified data format

Advantages:
(1) It is convenient for the front-end to better receive and analyze the data returned by the back-end data interface;
(2) Reduce the communication cost between the front-end and the back-end, just implement it in a certain format;
(3) It is conducive to the maintenance and
(4) It is conducive to the formulation of unified and standardized standards for back-end technologies .
Implementation:
(1) Create a class and add @ControllerAdvice;
(2) Implement the ResponseBodyAdvice interface, and rewrite supports and beforeBodyWrite (the unified object is implemented by this method)

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    
    
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
    
    
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    
    
        HashMap<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","");
        result.put("data",body);
        //String在转换时会出错  需要特殊处理,
        if (body instanceof String) {
    
    
            try {
    
    
                return objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
    
    
                e.printStackTrace();
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/qq_45283185/article/details/129496550