前言最近在维护一个运营端系统,和前端联调的过程中,经常需要排查一些交互问题。后端代码的输出参数,所以打算给HTTP接口增加一个输入输出日志。但是看现在的HTTP接口有点过分,那么最快的方法是什么呢?答案就是利用Spring的AOP功能,简单实用。思路是定义一个SpringAOP配置类,获取请求的URL,请求的入参,以及对应的输出参数,通过日志打印出来。SpringBoot的aop依赖:org.springframework.bootspring-boot-starter-aop例子1.写一个HTTP接口定义一个Controller,有里面只有一个方法,方法请求类型是get,输入输出参数都是简单的字符串字段。包com.example.springbootaoplog.controller;导入org.springframework.web.bind.annotation.GetMapping;导入org.springframework.web.bind.annotation.RequestMapping;导入org.springframework.web.bind.annotation.RestController;/***@author洪存林*/@RestController@RequestMapping("/index")publicclassIndexController{@GetMapping("/indexContent")publicStringindexContent(Stringparam){return"test";}}2.写一个AOP日志配置是本文的重点。定义一个AOP的内容,第一个是切点,第二个是请求前的日志打印,请求后的日志打印。包com.example.springbootaoplog.config;导入com.alibaba.fastjson.JSON;导入lombok.extern.slf4j.Slf4j;导入org.aspectj.lang.JoinPoint;导入org.aspectj.lang.annotation.AfterReturning;导入org.aspectj.lang.annotation.Aspect;导入org.aspectj.lang.annotation.Before;导入org.aspectj.lang.annotation.Pointcut;导入org.springframework.stereotype.Component;导入org.springframework.web.context.request.RequestContextHolder;导入org.springframework.web.context.request.ServletRequestAttributes;/***aop日志打印配置**@authorhongcunlin*/@Slf4j@Aspect@ComponentpublicclassAopLogConfig{/***切点路径:Controller层的所有方法*/@Pointcut("execution(public*com.example.springbootaoplog.controller.*.*(..))")publicvoidmethodPath(){}/***进入**@paramjoinPoint切点*/@Before(value=“methodPath()”)publicvoidbefore(JoinPointjoinPoint){ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();字符串url=requestAttributes.getRequest().getRequestURL().toString();log.info("请求={},输入={}",url,JSON.toJSONString(joinPoint.getArgs()));}/***退出**@paramres返回*/@AfterReturning(returning="res",pointcut="methodPath()")publicvoidafter(Objectres){ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();字符串url=requestAttributes.getRequest().getRequestURL().toString();log.info("request={},输入参数={}",url,JSON.toJSONString(res));}}3。结果测试我们使用浏览器的url对我们写的http接口发起get请求:可以看到,日志中打印了我们期望的请求的url和进出参数:说明我们的程序是正确的最后分享一下通过Spring的AOP功能打印HTTP接口的进出日志的方法。也说明越基础的东西越实用。