Spring AOP怎么实现打印HTTP接口出入参日志(aop,http,spring,开发技术)

时间:2024-05-03 19:25:24 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

接下来,请跟着小编一起来学习吧!

思路

定义个一个SpringAOP的配置类,里边获取请求的URL、请求的入参、相应的出参,通过日志打印出来。

SpringBoot的aop依赖:

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

示例

Spring AOP怎么实现打印HTTP接口出入参日志

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请求:

Spring AOP怎么实现打印HTTP接口出入参日志

可以看到,日志里边打印了我们预期的请求的URL和出入参了:

Spring AOP怎么实现打印HTTP接口出入参日志

说明我们的程序是正确的了。

若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

本文:Spring AOP怎么实现打印HTTP接口出入参日志的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:python压缩和解压缩模块之zlib怎么使用下一篇:

25 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18