springBoot aop拦截Controller参数获取

拦截Controller参数

    • 1 定义切点,创建自定义注解
    • 2 定义切面,解析自定义注解
    • 3 添加依赖

在进行后端测试的时候,一般情况需要知道后端实际接收到的参数的详细信息,为了避免手动创建log对象进行日志记录的打印,所以将 请求参数及响应内容日志打印交给切面来进行管理

通过自定义注解的方式,来实现 controller的入参、出参等的信息的日志打印

1 定义切点,创建自定义注解

import java.lang.annotation.*;

//注解不仅被保存到class文件中,jvm加载class文件之后,仍存在
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //注解添加的位置:controller方法上
@Documented
public @interface LogPrint {
    String description() default "";
}

2 定义切面,解析自定义注解

import com.alibaba.fastjson.JSONObject;
import com.hncj.annotation.LogPrint;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Enumeration;

@Aspect
@Component
//生产环境不进行日志打印参数,只对默认的yaml和application.yml和application.dev.yml生效
@Profile({"dev","test"}) 
@Slf4j
public class ParamLogAspect {
    /** 换行符 */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    /** 以自定义 @LogPrint 注解为切点 */
    // 这个地方换成自己的包路径
    @Pointcut("@annotation(com.hncj.annotation.LogPrint)")
    public void logPrint() {}

    /**
     * 在切点之前织入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("logPrint()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);

        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印描述信息
        log.info("Description    : {}", methodDescription);
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        log.info("Request Args   : {}", getParams(joinPoint));
        log.info("Request Arg1   : {}", getParams1(joinPoint));
        log.info("Request Arg1   : {}", getParams1(joinPoint));
    }

    /**
     * 在切点之后织入
     * @throws Throwable
     */
    @After("logPrint()")
    public void doAfter() throws Throwable {
        // 接口结束后换行,方便分割查看
        log.info("=========================================== End ===========================================" + LINE_SEPARATOR);
    }

    /**
     * 环绕 : 此方法是出参打印,
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */

    @Around("logPrint()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("Response Args  : {}",  JSONObject.toJSONString(result));
        // 执行耗时
        log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        return result;
    }


    /**
     * 获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     */
    public String getAspectLogDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(LogPrint.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }

    /**
     * 打印参数值
     * @param joinPoint
     * @return 缺点:不知道 参数名 与 参数值 的对应关系
     */
    private String getParams(JoinPoint joinPoint) {
        String params = "";
        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                Object arg = joinPoint.getArgs()[i];
                if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
                        || (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
                    continue;
                }
                try {
                    if(params.length() == 0){
                        params +=JSONObject.toJSONString(joinPoint.getArgs()[i]);
                    }else{
                        params = params + "," +  JSONObject.toJSONString(joinPoint.getArgs()[i]);
                    }
                } catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            }
        }
        return params;
    }


    /**
     * 同时拿到 参数名=参数值
     * @param joinPoint
     * @return
     */
    public String getParams1(JoinPoint joinPoint){
        String params = "";
        if( joinPoint.getArgs() != null && joinPoint.getArgs().length > 0  ){

            // 参数名称
            String[] names=((MethodSignature) joinPoint.getSignature()).getParameterNames();
            // 参数值
            //Object[] objects =  joinPoint.getArgs();

            for (int i = 0; i < joinPoint.getArgs().length; i++) {
                Object arg = joinPoint.getArgs()[i];
                if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
                        || (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
                    continue;
                }
                try{
                    if( params.length() == 0 ){
                        params += ( "" + names[i] + "=" + JSONObject.toJSONString(joinPoint.getArgs()[i]));
                    }else{
                        params += ( "," + names[i] + "=" + JSONObject.toJSONString(joinPoint.getArgs()[i]));
                    }
                }catch (Exception e1) {
                    log.error(e1.getMessage());
                }
            }
        }
        return params;
    }
}

使用方法

在需要拦截的方法上面加上注解即可

@LogPrint(description = "查看项目请求")
@GetMapping("/list")
public AjaxResult selectSysProject() {
    List<SysProject> sysProjectList = sysProjectService.selectSysProject();
    return AjaxResult.success(sysProjectList);
}

3 添加依赖

别忘了在pom.xml中添加AOP相关依赖


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-aopartifactId>
dependency>
 
<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>fastjsonartifactId>
    <version>1.2.41version>
dependency>

你可能感兴趣的:(JAVA实习,springboot,AOP)