Spring Aop achieve logging interceptor

AOP

Aspect Oriented Programming abbreviation for
Aspect Oriented Programming, by way of pre-compiler and run-time dynamic agent program features a technology to achieve a unified maintenance. (Put it more bluntly: we can without affecting the original function, the software scale . Function)
Then someone will ask, what is the rampant expansion of it? ? ?
A: Software development can be divided into "persistence", "business layer", the controller layer ";

So-called "transverse" refers to any of the three layers in the above mentioned layer!

After using AOP technology, using a method that can act simultaneously with all methods within a level.

You will be able to understand the word basic understanding of AOP!

AOP Surely it must be very familiar with, as one of the core Spring, which in the end What are the advantages of it?

1. reduce the coupling between the module
2. easy expansion of the system
3. A better code reuse

AOP scenarios

1. Log Processing
2. User login
3. Rights Management (the Authentication)
4. performance optimization (the Performance Optimization)
5. The transaction (Transactions)
6. The recording tracks Picture (logging, tracing, profiling and monitoring )
and the like. . .

How to use Spring Aop logging?

aop intercept all requests can be sent to all the clients, and a print request address, the name of the interface, a parameter value, the execution time of the method
1. The introduction of aop-dependent

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

2. Definitions section class

package com.xf.logistics.logisticsadmin.config;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * aop切面类
 * @author xufan
 * Aspect:标注该类为切面类  (@Aspect注解方式可以实现前置通知、返回通知、后置通知、异常通知、环绕通知。)
 * Component:把切面类加入到IOC容器中
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    private static final ThreadLocal<Date> beginTimeThreadLocal = new NamedThreadLocal<>("ThreadLocal beginTime");


    @Autowired(required = false)
    private HttpServletRequest request;

    // @Autowired
    //private CustomLogDao customLogDao; //引入dao层接口,目的是为了让日志持久化

    /**
     * PointCut表达式 :(切入点)切入到controller层,所有controller接口都进行切入 ,execution(要拦截的类路径)
     */
    @Pointcut("execution(* com.xf.logistics.web.*Controller.*(..))")
    public void controllerAspect() {
        log.info("controllerAspect");
    }


    /**
     * 前置通知 (在方法执行之前返回)用于拦截Controller层记录用户的操作的开始时间
     *
     * @param joinPoint 切点
     * @throws InterruptedException
     */
    @Before("controllerAspect()")
    public void doBefore(JoinPoint joinPoint) throws InterruptedException {
        //线程绑定变量(该数据只有当前请求的线程可见)
        Date beginTime = new Date();
        beginTimeThreadLocal.set(beginTime);
    }

    /**
     * 后置通知(在方法执行之后返回) 用于拦截Controller层操作
     *
     * @param joinPoint 切点
     */
    @After("controllerAspect()")
    public void after(JoinPoint joinPoint) {
        try {
            log.info("\nRequestURI={},Method={},\nParameterMap={},Cost={}",
                    //请求路径URI
                    request.getRequestURI(),
                    //请求方法名称
                    request.getMethod(),
                    //获取参数数组
                    JSONObject.toJSONString(Arrays.toString(joinPoint.getArgs())),
                    System.currentTimeMillis() - beginTimeThreadLocal.get().getTime());
            //执行日志入库操作

        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

}

3. Start project to test the interface control layer
Here Insert Picture Description
using the postman request
Here Insert Picture Description
4. Review the console, you will find our request has been intercepted, and the relevant information has been recorded
Here Insert Picture Description

to sum up

Use AOP, we use a method can handle all logging!

Published 36 original articles · won praise 15 · views 5498

Guess you like

Origin blog.csdn.net/weixin_44146379/article/details/105004517