Spring AOP怎么实现打印HTTP接口出入参日志
导读:本文共2071.5字符,通常情况下阅读需要7分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要:接下来,请跟着小编一起来学习吧!思路定义个一个SpringAOP的配置类,里边获取请求的URL、请求的入参、相应的出参,通过日志打印出来。SpringBoot的aop依赖:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-a... ...
目录
(为您整理了一些要点),点击可以直达。接下来,请跟着小编一起来学习吧!
思路
定义个一个SpringAOP的配置类,里边获取请求的URL、请求的入参、相应的出参,通过日志打印出来。
SpringBoot的aop依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
示例
1.编写一个HTTP接口
定义了一个Controller,里边就一个方法,方法请求类型是get,出入参都是简单的一个字符串字段。
packagecom.example.springbootaoplog.controller;importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;/*
@authorhongcunlin
*/
@RestController
@RequestMapping("/index")
publicclassIndexController{@GetMapping("/indexContent")
publicStringindexContent(Stringparam){
return"test";
}
}
2.编写一个AOP日志配置
这算是本文的重点了,定义一个AOP的内容,首先是切点,再者是请求前日志打印,最后请求后日志打印
packagecom.example.springbootaoplog.config;importcom.alibaba.fastjson.JSON;
importlombok.extern.slf4j.Slf4j;
importorg.aspectj.lang.JoinPoint;
importorg.aspectj.lang.annotation.AfterReturning;
importorg.aspectj.lang.annotation.Aspect;
importorg.aspectj.lang.annotation.Before;
importorg.aspectj.lang.annotation.Pointcut;
importorg.springframework.stereotype.Component;
importorg.springframework.web.context.request.RequestContextHolder;
importorg.springframework.web.context.request.ServletRequestAttributes;/
aop日志打印配置
@authorhongcunlin
/
@Slf4j
@Aspect
@Component
publicclassAopLogConfig{
/
切点路径:Controller层的所有方法
/
@Pointcut("execution(publiccom.example.springbootaoplog.controller..*(..))")
publicvoidmethodPath(){
}/*
入参
@paramjoinPoint切点
*/
@Before(value="methodPath()")
publicvoidbefore(JoinPointjoinPoint){
ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
Stringurl=requestAttributes.getRequest().getRequestURL().toString();
log.info("请求={},入参={}",url,JSON.toJSONString(joinPoint.getArgs()));
}/*
出参
@paramres返回
*/
@AfterReturning(returning="res",pointcut="methodPath()")
publicvoidafter(Objectres){
ServletRequestAttributesrequestAttributes=(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
Stringurl=requestAttributes.getRequest().getRequestURL().toString();
log.info("请求={},入参={}",url,JSON.toJSONString(res));
}
}
3.结果测试
我们通过浏览器的URL,针对我们编写的http接口,发起一次get请求:
可以看到,日志里边打印了我们预期的请求的URL和出入参了:
说明我们的程序是正确的了。
若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!Spring AOP怎么实现打印HTTP接口出入参日志的详细内容,希望对您有所帮助,信息来源于网络。