如何在Java-Spring服务中通过Swagger生成返回StreamingResponseBody的接口
问题:Swagger生成Spring流式下载接口的类型映射错误
需求背景
需要用OpenAPI/Swagger定义一个返回StreamingResponseBody的POST接口,因为待下载数据量极大,流式传输比字节数组更适合。
当前Swagger定义
responses: 200: description: Successful operation content: application/zip: schema: type: string format: binary
默认生成的API代码
按照上述定义,生成的接口返回类型是Resource,代码如下:
@RequestMapping( method = RequestMethod.POST, value = "/samples/export", produces = { "application/zip" }, consumes = { "application/json" } ) default ResponseEntity<org.springframework.core.io.Resource> _getExport( @Parameter(name = "SearchCriteria", description = "Supplies the preview filters", required = true) @Valid @RequestBody List<SearchCriteria> searchCriteria ) { return getExport(searchCriteria); }
尝试的类型映射配置
为了让生成的代码返回StreamingResponseBody,在插件中配置了类型映射:
<typeMapping> string+binary=org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody </typeMapping>
出现的编译错误
配置后生成了错误的类名——插件把完整包名转换成了驼峰式的类名OrgSpringframeworkWebServletMvcMethodAnnotationStreamingResponseBody,导致编译失败,错误代码如下:
@RequestMapping( method = RequestMethod.POST, value = "/samples/export", produces = { "application/zip" }, consumes = { "application/json" } ) default ResponseEntity<OrgSpringframeworkWebServletMvcMethodAnnotationStreamingResponseBody> _getExport( @Parameter(name = "SearchCriteria", description = "Supplies the preview filters", required = true) @Valid @RequestBody List<SearchCriteria> searchCriteria ) { return getExport(searchCriteria); }
解决方案
问题根源是类型映射的配置格式或解析逻辑问题,以下是几种可行的解决方式:
1. 修正XML配置格式
确保typeMapping标签内没有多余空格,并且正确嵌套在typeMappings下:
<configuration> <typeMappings> <typeMapping>string+binary=org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody</typeMapping> </typeMappings> </configuration>
2. 使用插件的configOptions配置(推荐)
如果是Maven插件,直接在configOptions中配置类型映射,避免XML解析时的空格或格式问题:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>请替换为最新版本</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>spring</generatorName> <configOptions> <typeMappings>string+binary=org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody</typeMappings> </configOptions> </configuration> </execution> </executions> </plugin>
3. 在Swagger定义中直接指定Java类型
无需全局配置,直接在Swagger的schema里用x-java-type指定返回类型:
responses: 200: description: Successful operation content: application/zip: schema: type: string format: binary x-java-type: org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
以上任意一种方式都能让生成器正确识别StreamingResponseBody类,避免编译错误。
内容的提问来源于stack exchange,提问作者Gabriela SO
相关产品推荐
相关产品推荐

