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

如何不使用Discriminator通过OpenAPI 3.0实现继承?或扩展类路径已有类?

问题解答

1. 不使用Discriminator生成Java继承结构

可以借助OpenAPI的扩展属性(配合OpenAPI Generator等代码生成器)实现目标继承结构,无需依赖discriminator:

OpenAPI配置示例

components:
  schemas:
    BaseClass:
      type: object
      x-java-abstract: true  # 指示生成器将该类设为抽象类
      properties:
        # 定义BaseClass的公共属性,无需鉴别符字段
        id:
          type: string

    Employee:
      allOf:
        - $ref: "#/components/schemas/BaseClass"
      properties:
        anotherThing:
          type: string

Jackson兼容处理

由于你已知目标类型,直接在序列化/反序列化时指定具体类型即可规避鉴别符报错:

// 反序列化:直接指定Employee类型
Employee employee = objectMapper.readValue(jsonContent, Employee.class);

// 序列化:Jackson默认支持继承结构的序列化
String json = objectMapper.writeValueAsString(employee);

若需全局配置消除类型推断逻辑,可给BaseClass添加Jackson注解(可通过OpenAPI的x-java-annotations扩展提前注入):

@JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
public abstract class BaseClass {
    // ...
}

2. 生成继承已有类的代码

通过OpenAPI的x-java-type扩展指定手动定义的BaseClass全限定类名,代码生成器会复用已有类而非重新生成:

OpenAPI配置示例

components:
  schemas:
    BaseClass:
      x-java-type: com.your.project.BaseClass  # 指向你手动编写的类路径

    Employee:
      allOf:
        - $ref: "#/components/schemas/BaseClass"
      properties:
        anotherThing:
          type: string

需确保使用的代码生成器(如OpenAPI Generator)支持x-java-type扩展,同时在生成配置中设置skipDefaultInterface等参数避免重复生成BaseClass。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:44:54