如何在OpenAPI 3.0中定义DTO继承以生成带Java继承的类?
如何让OpenAPI代码生成器通过继承实现子类?
我有3个实体:
- parent
- child_1
- child_2
我的OpenAPI定义如下:
Parent: description: Parent properties: id: $ref: '#/components/schemas/id' Child1: allOf: - $ref: '#/components/schemas/Parent' - type: object description: Child_1 properties: child1Fied: $ref: '#/components/schemas/child1Fied' Child2: allOf: - $ref: '#/components/schemas/Parent' - type: object description: Child_2 properties: child1Fied: $ref: '#/components/schemas/child2Fied'
我期望生成的类结构为:
Child1 extends Parent ... Child2 extends Parent ...
但实际生成的3个类相互独立:parent包含id字段,Child1包含自身的id和child1Fied字段,Child2包含自身的id和child2Fied字段。
是否有办法提示代码生成器通过继承实现这些类?
注:我未在OpenAPI官方的继承与多态文档中找到答案。
解决方案
要让代码生成器识别继承关系并生成子类继承父类的结构,需要在OpenAPI定义中明确添加多态相关关键字,具体步骤如下:
在父类中添加
discriminator(鉴别器)
鉴别器是代码生成器识别继承关系的关键标识,用于指定一个字段区分不同子类。修改Parent的定义:Parent: description: Parent type: object discriminator: propertyName: type # 自定义区分子类的字段名 properties: id: $ref: '#/components/schemas/id' type: type: string # 对应鉴别器的字段,需明确类型添加鉴别器映射(可选但推荐)
在父类的discriminator中添加mapping,明确子类对应的type值,让生成逻辑更清晰:Parent: description: Parent type: object discriminator: propertyName: type mapping: child1: '#/components/schemas/Child1' child2: '#/components/schemas/Child2' properties: id: $ref: '#/components/schemas/id' type: type: string确认子类
allOf定义正确性
你的子类通过allOf引用父类的写法是正确的,部分生成器可能需要子类显式声明type: object(你的定义已包含,可忽略此步)。适配特定生成器的配置
不同代码生成器可能需要额外配置启用继承生成:- 比如OpenAPI Generator的Java生成器,可添加参数
--enable-post-process-file,或在配置文件中设置inheritanceMode=INLINE; - 部分生成器默认会展开
allOf为独立字段,需通过配置强制启用继承逻辑。
- 比如OpenAPI Generator的Java生成器,可添加参数
验证修改后的完整定义
components: schemas: id: type: string child1Fied: type: string child2Fied: type: string Parent: description: Parent type: object discriminator: propertyName: type mapping: child1: '#/components/schemas/Child1' child2: '#/components/schemas/Child2' properties: id: $ref: '#/components/schemas/id' type: type: string Child1: allOf: - $ref: '#/components/schemas/Parent' - type: object description: Child_1 properties: child1Fied: $ref: '#/components/schemas/child1Fied' Child2: allOf: - $ref: '#/components/schemas/Parent' - type: object description: Child_2 properties: child2Fied: $ref: '#/components/schemas/child2Fied'
修改后,主流OpenAPI代码生成器会识别出继承关系,生成Child1 extends Parent、Child2 extends Parent的类结构,避免字段重复。
内容的提问来源于stack exchange,提问作者gstackoverflow
相关产品推荐
相关产品推荐

