使用jaxrs-spec生成OpenAPI接口,如何返回StreamingOutput而非File?
解决方案:将JAX-RS接口返回值改为StreamingOutput/Response(避免全局修改)
方案1:自定义扩展+轻量模板修改(推荐)
通过OpenAPI扩展指定单个接口的返回类型,配合极小的模板调整,实现仅目标接口修改返回值,其余接口保持原样。
步骤1:添加OpenAPI扩展
在你的接口定义中,为getDocument操作添加自定义扩展x-codegen-response-type,指定想要的返回类型:
/documents/{id}: get: summary: Get the given document as PDF operationId: getDocument x-codegen-response-type: javax.ws.rs.core.StreamingOutput # 指定返回StreamingOutput parameters: - name: id in: path required: true schema: type: string responses: 200: description: Get the document content: application/pdf: schema: type: string format: binary 302: description: Redirect to the location of the PDF document headers: Location: description: The URL from where to get the PDF document schema: type: string 404: description: Document not found
如果想要返回Response,将扩展值改为javax.ws.rs.core.Response即可。
步骤2:微调接口模板
- 在项目中创建模板目录:
src/main/resources/openapi-generator/templates - 从OpenAPI Generator 6.2.0版本的jaxrs-spec模板中,复制
api.mustache文件到上述目录 - 修改模板中返回值的判断逻辑,优先使用自定义扩展指定的类型:
{{#x-codegen-response-type}}{{{x-codegen-response-type}}}{{/x-codegen-response-type}}{{^x-codegen-response-type}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}{{/x-codegen-response-type}} {{operationId}}({{#allParams}}{{>param}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
步骤3:重新生成接口
运行Maven插件后,目标接口的返回值会变为指定类型,其余接口保持默认生成逻辑:
@GET @Path("/{id}") @Produces({ "application/pdf" }) StreamingOutput getDocument(@PathParam("id") String id);
方案2:全局返回Response的折中处理
如果你可以接受后续少量调整,也可以在Maven插件配置中添加returnResponse=true,让所有接口统一返回Response:
<configOptions> <!-- 原有配置 --> <returnResponse>true</returnResponse> </configOptions>
这种方式无需修改模板,但需要同步调整所有接口的实现类和测试代码。
内容的提问来源于stack exchange,提问作者Kariem
相关产品推荐
相关产品推荐

