You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI Generator生成ChildClass未继承ParentClass的问题

解决OpenAPI Generator 6.2.1生成类继承结构的问题

要让OpenAPI Generator生成ChildClass extends ParentClass的继承结构,而非合并父类属性的组合类,需要从Gradle配置和OpenAPI规范两个方面调整:

1. 修改Gradle的OpenAPI生成配置

在build.gradle的openApiGenerate任务中,添加configOptions开启继承支持:

openApiGenerate {
    generatorName = "spring"
    inputSpec = "$rootDir/src/main/resources/openapi.json".toString()
    outputDir = "$buildDir/generated".toString()
    apiPackage = "com.example.api" // 替换为你的API包路径
    modelPackage = "com.example.model" // 替换为你的Model包路径
    configOptions = [
        useInheritance: "true",
        inheritAllOf: "true"
    ]
}
  • useInheritance: 开启生成代码的继承特性
  • inheritAllOf: 明确将allOf引用的父类处理为继承关系,而非属性合并

2. 调整OpenAPI规范(openapi.json)

确保你的schema定义符合以下要求:

  • 父类ParentClass必须是独立定义的schema,不能是匿名结构
  • ChildClass的allOf数组中,父类引用必须放在第一个位置

示例规范:

{
  "openapi": "3.0.3",
  "components": {
    "schemas": {
      "ParentClass": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int64"
          },
          "name": {
            "type": "string"
          }
        }
      },
      "ChildClass": {
        "allOf": [
          { "$ref": "#/components/schemas/ParentClass" },
          {
            "type": "object",
            "properties": {
              "childSpecificField": {
                "type": "string"
              }
            }
          }
        ]
      }
    }
  }
}

3. 验证效果

执行Gradle生成任务:

./gradlew openApiGenerate

生成的ChildClass代码会自动继承ParentClass,示例如下:

package com.example.model;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.example.model.ParentClass;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;

/**
 * ChildClass
 */
@Validated
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2024-05-20T12:34:56.789+08:00")


public class ChildClass extends ParentClass  {
  @JsonProperty("childSpecificField")
  private String childSpecificField = null;

  // 省略getter、setter、equals、hashCode等方法
}

内容的提问来源于stack exchange,提问作者Gamzy joy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 17:45:16