很长一段时间过去了,但其他人可能会从中受益:
您可以定义一个@Around 方面并拦截传入的请求及其各自的主体,如下所示:
@Aspect
@Component
public class RequestResponseLoggingAdvice {
private static final Logger logger = LoggerFactory.getLogger(RequestResponseLoggingAdvice.class);
@Pointcut("within(@org.springframework.web.bind.annotation.RestController*)")
public void restcontroller() {}
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void postmapping() {}
@Around("restcontroller() && postmapping() && args(.., @RequestBody body, request)")
public Object logPostMethods(ProceedingJoinPoint joinPoint, Object body, HttpServletRequest request) throws Throwable {
logger.debug(request.toString()); // You may log request parameters here.
logger.debug(body.toString()); // You may do some reflection here
Object result;
try {
result = joinPoint.proceed();
logger.debug(result.toString());
} catch(Throwable t) {}
}
}
请注意,您的 REST 控制器方法必须具有适合上述方面的签名才能挂钩。示例如下:
@PostMapping
public SampleDTO saveSample(@RequestBody Sample sample, HttpServletRequest request) {
//.....
}