如何配置OpenAPI Generator生成不含ResponseEntity的Java API
问题
我想用OpenAPI 3.0生成Java API,但不想让任何返回类型是ResponseEntity。目前通过.yaml文件生成的API(已移除大量注解)如下:
@GetMapping(value = "/student", produces = { "application/json" }) ResponseEntity<List<Student>> getAllStudents();
但雇主要求的API格式是:
@GetMapping(value = "/student") List<Student> getAllStudents();
我找不到能让代码生成器不使用ResponseEntity的配置选项,请问有没有办法通过配置OpenAPI Generator实现这一需求?
详情
我用Maven构建,pom文件中的代码生成配置如下:
<build> <plugins> <plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <!-- RELEASE_VERSION --> <version>5.0.0-SNAPSHOT</version> <!-- /RELEASE_VERSION --> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/OpenApi.yaml</inputSpec> <generatorName>spring</generatorName> <groupId>com.dummy.example</groupId> <artifactId>dummy</artifactId> <artifactVersion>2.0</artifactVersion> <library>spring-boot</library> <packageName>com.neptunedreams.configuration</packageName> <apiPackage>com.neptunedreams.api</apiPackage> <invokerPackage>com.neptunedreams</invokerPackage> <modelPackage>com.neptunedreams.model</modelPackage> <configOptions> <sourceFolder>src/main/java</sourceFolder> <bigDecimalAsString>true</bigDecimalAsString> <dateLibrary>java8</dateLibrary> <interfaceOnly>true</interfaceOnly> <library>spring-boot</library> <skipDefaultInterface>true</skipDefaultInterface> </configOptions> </configuration> </execution> </executions> </plugin> </plugins> </build>
我的yaml文件内容很基础:
openapi: 3.0.0 info: description: StackOverflow ResponseEntity Question version: 1.0.0 title: ResponseEntity Question paths: /student: get: summary: Get all students operationId: getAllStudents responses: 200: description: Get all students content: application/json: schema: type: array items: $ref: '#/components/schemas/Student' components: schemas: Student: type: object properties: name: type: string id: type: integer format: int64 required: - name - id
解决方案
- 在Maven插件的
configOptions中添加<useResponseEntity>false</useResponseEntity>,这会让生成的API直接返回业务对象类型,不再用ResponseEntity包裹。 - 若要去掉
@GetMapping中的produces参数,可额外添加<producesOptional>true</producesOptional>配置,当接口响应内容为默认JSON类型时,生成器会自动省略该参数。
修改后的configOptions片段如下:
<configOptions> <sourceFolder>src/main/java</sourceFolder> <bigDecimalAsString>true</bigDecimalAsString> <dateLibrary>java8</dateLibrary> <interfaceOnly>true</interfaceOnly> <library>spring-boot</library> <skipDefaultInterface>true</skipDefaultInterface> <!-- 禁用ResponseEntity包裹 --> <useResponseEntity>false</useResponseEntity> <!-- 可选:省略默认的produces参数 --> <producesOptional>true</producesOptional> </configOptions>
注意:useResponseEntity配置从OpenAPI Generator 4.3.0版本开始支持,你当前使用的5.0.0-SNAPSHOT版本完全兼容该配置。
内容的提问来源于stack exchange,提问作者MiguelMunoz
相关产品推荐
相关产品推荐

