如何让OpenAPI生成器输出带? extends Object的Spring控制器接口
实现
ResponseEntity<? extends Object>的生成方案 1. OpenAPI 描述配置
要让生成器识别到返回类型是Object的子类,需要在OpenAPI规范中定义多态响应类型,通过allOf关联基础响应与具体响应:
openapi: 3.0.3 info: title: Version Push API version: 1.0.0 components: schemas: # 定义基础响应结构(所有响应的父类) BaseApiResponse: type: object properties: code: type: integer message: type: string # 成功响应,继承基础响应 VersionPushSuccess: allOf: - $ref: '#/components/schemas/BaseApiResponse' properties: versionList: type: array items: type: object properties: versionId: type: string status: type: string # 错误响应,同样继承基础响应 VersionPushError: allOf: - $ref: '#/components/schemas/BaseApiResponse' properties: errorDetails: type: string paths: /versions/push: post: summary: Push version data responses: '200': description: Push successful content: application/json: schema: $ref: '#/components/schemas/VersionPushSuccess' '400': description: Invalid request content: application/json: schema: $ref: '#/components/schemas/VersionPushError'
2. OpenAPI Generator 配置
在生成器的配置中开启泛型响应支持,以Maven插件为例:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>spring</generatorName> <configOptions> <!-- 核心配置:开启泛型响应生成 --> <useGenericResponse>true</useGenericResponse> <!-- 强制返回ResponseEntity包装类 --> <returnResponse>true</returnResponse> </configOptions> </configuration> </execution> </executions> </plugin>
如果用Gradle,配置如下:
plugins { id "org.openapi.generator" version "6.6.0" } openapiGenerate { generatorName = "spring" inputSpec = file("src/main/resources/openapi.yaml").absolutePath configOptions = [ useGenericResponse: "true", returnResponse: "true" ] }
关键说明
useGenericResponse: true是核心开关,它会让生成器根据多响应类型,生成带通配符的泛型? extends Object,而非固定的Object。- 必须定义多个继承自基础Object结构的响应Schema,这样生成器才能识别到返回类型是Object的子类集合。
内容的提问来源于stack exchange,提问作者Julien Berthoud
相关产品推荐
相关产品推荐

