【发布时间】:2015-11-24 17:44:59
【问题描述】:
在我的 spring rest 应用程序中,我在方面记录每个 api 端点参数。
@Aspect
@Component
public class EndpointsAspect {
@Around("execution(@org.springframework.web.bind.annotation.RequestMapping * *(..))")
public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
Map<String, Object> log = new HashMap<>();
String[] parameterNames = methodSignature.getParameterNames();
Object[] parameterValues = joinPoint.getArgs();
Map<String, Object> arguments = new HashMap<>();
for (int i = 0; i < parameterNames.length; i++) {
arguments.put(parameterNames[i], parameterValues[i]);
}
log.put("Method arguments", arguments);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(log);
...
Object retVal = joinPoint.proceed();
}
}
它工作正常,直到建议方法的参数之一具有 HttpServletRequest 类型的参数
@RequestMapping("/info")
public String index(HttpServletRequest request) {
return "Info";
}
在这种情况下会引发 java.lang.StackOverflowError。
我知道这在某种程度上与 HttpServlterRequest 变量有关(可能是一些不定式循环),但是如何解决这个问题呢?
如何限制 gson 深度?
我查看了一些解决方案(使用一些注释来注释应该转换为 json 的字段或类),但它不适合我,这应该是所有类和案例的通用解决方案(我不能,因为例如,用一些注释对 HttpServletRequest 进行注释,或者将其包含在 gson 排除策略中,因为现在谁的类将被转换为 json),我需要将日志数据作为 json,但由于序列化问题,记录器不应该是应用程序故障点。
谢谢。
【问题讨论】: