SpringBoot AOP 方法出入参数打印

c4fa3dae2370826a9716c17bd8244bf3.jpg

引言

在项目中,不管是在开发阶段和后续的维护阶段,前后端调用的出入参都是有很大作用的,可以帮助我们及时排查和定位问题。

常见的做法是通过AOP实现,在Controller方法执行前后打印出入参。由于实现比较简单,需要了解AOP,网上的教程也很多,这里就不多说,直接给出一个示例,以供大家参考。

环境

组件名称版本
JDK17
SpringBoot3.2.0

实现

说明:

  1. 切点是定义在使用@RestController注解类的所有方法上

  2. @Before 注解指定的方法在切面切入目标方法之前执行

  3. @AfterReturning捕获方法执行后的返回值

 

ini

复制代码

package com.zl.test.config.log; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; 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 java.util.Map; @Slf4j @Aspect @Component public class AopLogConfig { @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)") public void controllerPointCut() { } @Before(value = "controllerPointCut()") public void before(JoinPoint joinPoint) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); String url = requestAttributes.getRequest().getRequestURL().toString(); Map<String, String[]> parameterMap = requestAttributes.getRequest().getParameterMap(); Object[] args = joinPoint.getArgs(); Object[] arguments = new Object[args.length]; for (int i = 0; i < args.length; i++) { if (args[i] instanceof ServletRequest || args[i] instanceof ServletResponse || args[i] instanceof MultipartFile) { continue; } arguments[i] = args[i]; } String body = JSONObject.toJSONString(arguments); log.info("请求URL: {}, 请求参数: {}, 请求body: {}", url, JSON.toJSONString(parameterMap), body); } @AfterReturning(returning = "res", pointcut = "controllerPointCut()") public void after(Object res) { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); String url = requestAttributes.getRequest().getRequestURL().toString(); log.info("请求URL: {}, 返回值: {}", url, JSON.toJSONString(res)); } }

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值