Swagger-ui无法查看@RequestBody参数,POST请求参数添加失败求助
问题解决步骤
1. 移除依赖冲突
你的pom.xml同时引入了springdoc-openapi和springfox两个OpenAPI/Swagger实现框架,二者会相互干扰,导致参数无法正常显示。必须保留其中一个,建议移除springfox依赖:
<!-- 移除这个冲突依赖 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
同时,swagger-models和swagger-parser-v3属于swagger-core系列,springdoc已包含相关依赖,可一并移除简化配置:
<!-- 可移除,springdoc自带相关依赖 --> <dependency> <groupId>io.swagger.core.v3</groupId> <artifactId>swagger-models</artifactId> <version>2.2.20</version> </dependency> <dependency> <groupId>io.swagger.parser.v3</groupId> <artifactId>swagger-parser-v3</artifactId> <version>2.1.20</version> </dependency>
2. 修正Form参数的接收方式与注解
如果你的Form类包含file(文件)字段,@RequestBody无法处理multipart/form-data类型的请求,这是Swagger不显示参数的核心原因之一。需要调整如下:
调整Controller方法
改用@ModelAttribute接收表单参数,并指定请求的内容类型:
@Operation(summary = "Send a mail. It is possible to add to the mail a carbon copy and attachments.") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Mail sent successfully "), @ApiResponse(responseCode = "404", description = "Something went wrong while sending the email.", content = @Content) }) @PostMapping(value = "/send", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public void sendMailWithTemplate(@ModelAttribute Form form) { emailService.sendMail(form.getTo(), form.getCc(), form.getSubject(), form.getText(), form.getFile()); }
完善Form类的Swagger注解
确保Form类有Lombok的@Data注解(生成getter/setter),并添加OpenAPI的@Schema注解标记字段,让Swagger识别参数结构:
import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import org.springframework.web.multipart.MultipartFile; @Data @Schema(description = "邮件发送表单参数") public class Form { @Schema(description = "收件人邮箱", required = true) private String to; @Schema(description = "抄送人邮箱") private String cc; @Schema(description = "邮件主题", required = true) private String subject; @Schema(description = "邮件内容", required = true) private String text; @Schema(description = "附件文件") private MultipartFile file; }
3. 清理缓存并重启应用
执行mvn clean install清理项目依赖缓存,然后重启Spring Boot应用,访问http://localhost:8080/swagger-ui/index.html(springdoc 2.x默认路径)验证参数是否正常显示。
内容的提问来源于stack exchange,提问作者Bronka
相关产品推荐
相关产品推荐

