Springfox开发multipart/form-data接口@ModelAttribute参数Swagger注解失效问题
问题原因
springfox-boot-starter 3.0.0默认的参数解析逻辑,对multipart/form-data类型的请求,不会自动读取@ModelAttribute绑定的实体类内部的@ApiModelProperty注解,仅会识别直接声明在接口方法上的@ApiParam注解,这是框架本身的兼容缺陷。而application/json类型的请求走的是请求体解析逻辑,会正常读取实体类的注解信息,所以才会出现你观察到的差异。
解决方案
不需要修改接口的consumes配置,仅需新增自定义Swagger参数解析插件即可,步骤如下:
- 清理冗余注解
删除MyModelRequest类字段上的所有@ApiParam注解,仅保留@ApiModelProperty即可,两类注解同时存在可能触发优先级冲突。
修改后的实体类示例:
@ApiModel @Data public class MyModelRequest { @ApiModelProperty(value = "name model description", example = "summer picture", required = true) private String name; @DecimalMin("0.00") @DecimalMax("100.00") @ApiModelProperty(value = "Minimum required accuracy", example = "95.15", required = false) private BigDecimal accuracy; @ApiModelProperty(value = "Separation between top item and the image", example = "300", required = false) private Integer marginTop; @ApiModelProperty(value = "The image to be stored", example = "vacations.png", required = true) private MultipartFile image; }
- 新增自定义Swagger配置插件
在项目中新增Swagger配置类,注册multipart/form-data类型请求的参数解析插件,让框架支持读取实体类内部的@ApiModelProperty注解:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.OperationModelsProviderPlugin; import springfox.documentation.spi.service.contexts.RequestMappingContext; import springfox.documentation.spring.web.readers.operation.OperationModelsProvider; import org.springframework.web.bind.annotation.ModelAttribute; @Configuration public class SwaggerCustomConfig { @Bean @Order(OperationModelsProvider.DEFAULT_ORDER + 10) public OperationModelsProviderPlugin modelAttributeFormDataSupportPlugin() { return new OperationModelsProviderPlugin() { @Override public void apply(RequestMappingContext context) { // 仅处理multipart/form-data类型的请求 if (context.getConsumes().stream().noneMatch(t -> "multipart/form-data".equals(t.toString()))) { return; } // 识别@ModelAttribute绑定的实体类,将其加入Swagger的模型解析范围 context.getParameters().stream() .filter(param -> param.findAnnotation(ModelAttribute.class).isPresent()) .forEach(param -> context.operationModelsBuilder().addInputParam(param.getParameterType())); } @Override public boolean supports(DocumentationType documentationType) { return DocumentationType.OAS_30.equals(documentationType) || DocumentationType.SWAGGER_2.equals(documentationType); } }; } }
- 重启项目验证
清理项目缓存后重启服务,此时Swagger文档中multipart/form-data类型的接口会正常显示所有字段的描述、示例、必填标记,同时文件上传功能完全不受影响。
内容的提问来源于stack exchange,提问作者Clamari
相关产品推荐
相关产品推荐

