You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用Swagger 3的RequestBody注解?请求参数重复显示排查

排查方向与解决方案

一、修正注解使用方式

你当前错误地在方法参数上叠加了Swagger的@io.swagger.v3.oas.annotations.parameters.RequestBody注解,正确的做法是将请求体描述配置在@Operation注解内部,而非参数上。调整后的代码示例:

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import jakarta.validation.Valid;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;

@PostMapping(value = "/login", consumes = MediaType.APPLICATION_JSON_VALUE)
@PermitAll
@Operation(
    summary = "login by username and password",
    requestBody = @RequestBody(
        description = "login request body",
        required = true,
        content = @Content(
            schema = @Schema(implementation = AuthLoginReqVO.class)
        )
    )
)
@OperateLog(enable = false)
public CommonResult<AuthLoginRespVO> login(
    @RequestBody @Valid AuthLoginReqVO reqVO
){
    return success(authService.login(reqVO));
}

二、核心排查方向

  • 检查Swagger依赖版本与类型:确认项目使用的是SpringDoc OpenAPI还是旧版Springfox。如果是Springfox,需改用对应版本的请求体注解;若为SpringDoc,需确保依赖版本(如springdoc-openapi-starter-webmvc-ui)与Spring Boot版本兼容,避免注解解析逻辑冲突。
  • 排查全局Swagger配置类:检查项目中是否存在自定义的Swagger插件(如实现ParameterBuilderPlugin、OperationBuilderPlugin接口的Bean),这类插件可能错误地将@RequestBody参数解析为查询参数,导致字段重复显示。
  • 校验@RequestBody注解包路径:确保导入的是org.springframework.web.bind.annotation.RequestBody,而非其他包的同名注解,否则Spring和Swagger无法正确识别请求体参数类型。
  • 明确接口请求媒体类型:在@PostMapping中指定consumes = MediaType.APPLICATION_JSON_VALUE,避免Swagger因兼容多类型请求,将请求体字段同时解析为表单参数显示在参数栏。
  • 检查实体类注解配置:给实体类的@Schema添加正确描述(如@Schema(description = "登录请求参数")),避免空描述导致Swagger解析逻辑异常。

内容的提问来源于stack exchange,提问作者赵震宇

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 22:58:22