如何让OpenAPI生成的类中Schema属性复用指定通用数据类型?
解决OpenAPI生成Java类时body属性类型不符合预期的问题
你的问题出在Schema定义里用了allOf包裹单个$ref引用,代码生成工具会把这个结构识别成新的匿名Schema,自动生成SignupRequestBody这类中间类,而不是直接复用你定义好的UserCreateOrUpdateRequest。
问题原因
allOf关键字的作用是组合多个不同的Schema,当你只用它包裹单个$ref时,生成工具会认为你要创建一个基于目标Schema的新复合结构,而非直接引用原类,因此会额外生成中间类来承载这个结构。
解决方法
直接把body属性设置为$ref引用,去掉多余的allOf包裹:
修改后的userapi.yaml Schema:
SignupRequest: type: object description: Request model for user registration properties: body: $ref: '#/components/schemas/UserCreateOrUpdateRequest' UserUpdateRequest: type: object properties: body: $ref: '#/components/schemas/UserCreateOrUpdateRequest'
这样生成的Java类就会符合你的预期:
public class UserUpdateRequest { private UserCreateOrUpdateRequest body //getters and setters generated using lombok } public class SignupRequest { private UserCreateOrUpdateRequest body //getters and setters generated using lombok }
如果你后续确实需要用allOf组合多个Schema,可以通过配置生成工具参数来避免生成中间类(比如OpenAPI Generator的--additional-properties useSingleSchemaProperty=true),但当前场景下,直接去掉allOf是最简单直接的方案。
内容的提问来源于stack exchange,提问作者Shreyansh Jain
相关产品推荐
相关产品推荐

