springboot aop 打印请求参数
很多时候为了查找问题方便,可能会需要用到前端请求后台的请求参数,以及后端返回的参数;同时还可以添加logback将日志文件输出到指定的目录下面,尤其是我们无法进行连接本机联调的情况下,部署到服务器,我们可以看日志文件的请求参数,在本机模拟就可以;
但是很多时候,我们其实可以使用swagger,以后再更新吧;
1.首先需要在pom.xml添加aop依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.创建一个类LogAspect:
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* springboot aop 打印参数filter
* @author xuming
*/
@Aspect
@Component
@Order(1)
@Slf4j
public class LogAspect {
@Around("execution(* com.org..*Controller.*(..)) )")
public Object aroundController(ProceedingJoinPoint proceedingJoinPoint){
String methodName =proceedingJoinPoint.getSignature().getName();
Object result=null;
Object[] arrays = proceedingJoinPoint.getArgs();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
try {
log.info(request.getServletPath()+", request params: "+ JSONObject.toJSONString(proceedingJoinPoint.getArgs()));
result=proceedingJoinPoint.proceed();
log.info(request.getServletPath()+", response result :"+JSONObject.toJSONString(result));
} catch (Throwable e) {
log.error(request.getServletPath()+" occurs exception :"+ e, e);
e.printStackTrace();
}
//后置通知
return result;
}
}
然后你就可以看在控制台看到结果喽!