如何用OpenAPITools生成MultipartFile集合处理二进制数组?
解决方案:将OpenAPI二进制数组生成Spring MultipartFile集合
针对OpenAPITools openapi-generator-cli v5版本,要把如下OpenAPI定义的二进制数组生成org.springframework.web.multipart.MultipartFile类型集合:
type: array items: type: string format: binary
可尝试以下几种方案:
方案1:配置参数组合(优先推荐)
在生成命令中添加type-mappings、import-mappings和useMultipartForBinary参数,覆盖默认的类型映射:
openapi-generator-cli generate \ -i 你的OpenAPI规范文件.yaml \ -g spring \ --type-mappings string_binary=org.springframework.web.multipart.MultipartFile \ --import-mappings org.springframework.web.multipart.MultipartFile=org.springframework.web.multipart.MultipartFile \ --additional-properties useMultipartForBinary=true
useMultipartForBinary=true:让生成器优先处理二进制类型为MultipartFiletype-mappings:将string/binary类型映射为MultipartFileimport-mappings:确保生成代码时自动导入正确的包
方案2:修改Mustache模板
如果参数配置无效,可自定义API模板来强制替换数组项类型:
- 从OpenAPI Generator源码中复制Spring代码生成器的
api.mustache模板到本地目录 - 修改模板中处理数组参数的片段,判断当数组项为
binary格式时,使用MultipartFile:
{{#isArray}} {{#items.format}} {{#isBinary}}List<org.springframework.web.multipart.MultipartFile>{{/isBinary}} {{^isBinary}}List<{{complexType}}>{{/isBinary}} {{/items.format}} {{^items.format}}List<{{complexType}}>{{/items.format}} {{/isArray}} {{^isArray}} {{#format}} {{#isBinary}}org.springframework.web.multipart.MultipartFile{{/isBinary}} {{^isBinary}}{{complexType}}{{/isBinary}} {{/format}} {{^format}}{{complexType}}{{/format}} {{/isArray}}
- 生成命令中指定自定义模板目录:
openapi-generator-cli generate \ -i 你的OpenAPI规范文件.yaml \ -g spring \ -t /本地模板目录路径
方案3:自定义Codegen扩展(进阶)
如果前两种方案都不满足需求,可继承SpringCodegen类重写类型处理逻辑:
- 创建自定义Codegen类,重写
getSwaggerType方法,针对二进制数组返回MultipartFile集合:
public class CustomSpringCodegen extends SpringCodegen { @Override public String getSwaggerType(String swaggerType) { if ("array".equals(swaggerType) && this.currentParameter != null) { Schema itemsSchema = currentParameter.getSchema().getItems(); if (itemsSchema != null && "string".equals(itemsSchema.getType()) && "binary".equals(itemsSchema.getFormat())) { return "List<org.springframework.web.multipart.MultipartFile>"; } } return super.getSwaggerType(swaggerType); } }
- 将类打包成jar文件,生成命令中指定自定义Codegen:
openapi-generator-cli generate \ -i 你的OpenAPI规范文件.yaml \ -g custom-spring \ --library /自定义Codegen jar路径
内容的提问来源于stack exchange,提问作者Niko
相关产品推荐
相关产品推荐

