本篇文章小编给大家分享一下SpringBoot使用Aspect切面拦截打印请求参数代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
AspectJ作为语言级别的AOP框架,功能相比于SpringAOP更加强大。SpringAOP旨在提供给用户一个轻量级的AOP实现方案,它只能应用在SpringIOC容器中管理的bean。而AspectJ旨在提供给用户一个完整的AOP解决方案,它可以应用在所有的域对象中,下面给大家介绍SpringBoot使用Aspect切面拦截打印请求参数的代码。
引入依赖
org.springframework.boot spring-boot-starter-aop
也用到了fastjson打印参数 , 如果引了就不需要(也可以根据自己的来打印)
com.alibaba
fastjson
1.2.15
LogAspect.java
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
/**
* @author zhipeih
* @date 2021/07/14
*/
@Slf4j
@Component
@Aspect //表示它是一个切面
public class LogAspect {
/**
*
* execution:改成自己要打印的控制器路径
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around("execution(* com.example.*.controller.*.*(..)) ")
public Object handleControllerMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//原始的HTTP请求和响应的信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
//获取当前执行的方法
Method targetMethod = methodSignature.getMethod();
//获取参数
Object[] objects = proceedingJoinPoint.getArgs();
//获取返回对象
Object object = proceedingJoinPoint.proceed();
StringBuilder sb = new StringBuilder(1000);
sb.append("-------------------------------------------------------------n");
sb.append("Controller: ").append(targetMethod.getDeclaringClass().getName()).append("n");
sb.append("Method : ").append(targetMethod.getName()).append("n");
sb.append("Params : ").append(JSON.toJSONString(objects)).append("n");
sb.append("URI : ").append(request.getRequestURI()).append("n");
sb.append("URL : ").append(request.getRequestURL()).append("n");
sb.append("Return : ").append(object).append("n");
sb.append("-------------------------------------------------------------n");
System.out.println(sb);
return proceedingJoinPoint.proceed();
}
}