首页  >  文章  >  DTO 序列化期间 Spring Boot 应用程序中出现 StackOverflowError 问题

DTO 序列化期间 Spring Boot 应用程序中出现 StackOverflowError 问题

王林
王林转载
2024-02-05 23:06:04556浏览
问题内容

当我尝试序列化具有自引用关系的 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"
}

问题:

  1. 如何修改 nodeattributesdto 类中的 tostring 方法以避免序列化期间出现 stackoverflowerror?
  2. 在处理 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。

请参阅:如何忽略 json 中的字段回应?

这里有很多好信息:https://www.php.cn/link/ffe4a40fecc90fa1120088e704712fb2

它还可能有助于在代码生成工具(如 jhipster)之外创建一个简单的 Web 服务,以了解幕后发生的情况,从而更好地控制生成。

以上是DTO 序列化期间 Spring Boot 应用程序中出现 StackOverflowError 问题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除