当我尝试序列化具有自引用关系的 dto 类 (nodeattributesdto) 时,我在 spring boot 应用程序中遇到 stackoverflowerror。该错误发生在执行dto类中的tostring方法期间。
nodeattributes.java:
// relevant parts of nodeattributes.java @onetomany(mappedby = "parent") @cache(usage = cacheconcurrencystrategy.read_write) @jsonignoreproperties(value = { "children", "parent", "node" }, allowsetters = true) private set<nodeattributes> children ; @manytoone @jsonignoreproperties(value = { "children", "parent", "node" }, allowsetters = true) private nodeattributes parent; // other fields, getters, setters, etc.
nodeattributesdto.java:
// relevant parts of nodeattributesdto.java private set<nodeattributesdto> children; private nodeattributesdto parent; // getters, setters, and other methods... @override public string tostring() { return "nodeattributesdto{" + "id=" + getid() + // other fields... ", parent=" + getparent() + ", children=" + getchildren() + ", node=" + getnode() + "}"; }
postmapping 请求正文:
{ // some other fields... "children": [ { "key": "attribute412w", "value": "value3", "valuetype": "integer", "type": "response", "required": false, "enabled": true, "node": { "id": 26030 } } ], // other fields... }
错误:
{ "type": "https://www.jhipster.tech/problem/problem-with-message", "title": "Internal Server Error", "status": 500, "detail": "Handler dispatch failed; nested exception is java.lang.StackOverflowError", "path": "/api/node-attributes", "message": "error.http.500" }
问题:
- 如何修改 nodeattributesdto 类中的 tostring 方法以避免序列化期间出现 stackoverflowerror?
- 在处理 dto 中的自引用关系时,我是否应该考虑特定的 jackson 注释或配置?
环境: 春季启动版本:2.7.2 java版本:17 数据库:postgresql
我已经尝试过:
- 不同的 jackson 注释(@jsonmanagedreference、@jsonbackreference)
正确答案
我相信您的困惑是 toString 不控制 Spring Boot 中的编组。
如果您要通过 System.err.println() 记录该对象以表示标准错误,它将使用该 toString。
似乎您的 toString 本质上是试图成为数据的递归转储,但并不正确。我认为这只是基本的 Java/CS。
在toString中,您可以只打印当前节点的数据,然后对所有子节点调用toString(delagate)。应该可以做到这一点。我认为一般情况下您不需要反向引用(对于 toString),因为您将从“树”的顶部开始。
编组器检查对象并使用反射来组成序列化表示。正如您所注意到的,它将遵守某些注释。例如@JsonIgnore。
这里有很多好信息:https://www.php.cn/link/ffe4a40fecc90fa1120088e704712fb2
它还可能有助于在代码生成工具(如 jhipster)之外创建一个简单的 Web 服务,以了解幕后发生的情况,从而更好地控制生成。
以上是DTO 序列化期间 Spring Boot 应用程序中出现 StackOverflowError 问题的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。