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

Spring Boot 3集成springdoc-openapi时/v3/api-docs报400错误求助

问题:Spring Boot 3中springdoc-openapi加载API定义失败(400错误)

环境配置

依赖配置

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.0.2</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-api</artifactId>
    <version>2.0.2</version>
</dependency>

控制器代码

@OpenAPIDefinition(
    info = @Info(
        title = "Test Application",
        description = "Description"
    )
)
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class TestController {

    @Operation(summary = "Test endpoint")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "204", description = "OK", content = @Content),
        @ApiResponse(responseCode = "400", description = "Invalid request", content = @Content),
        @ApiResponse(responseCode = "500", description = "Internal server error", content = @Content)})
    @PostMapping("/test")
    public ResponseEntity<Object> test(@RequestBody @Valid @ParameterObject TestRequest testRequest, BindingResult bindingResult) {
        ...
    }
}

错误现象

访问http://localhost:8080/swagger-ui/index.html时,页面提示“Failed to load API definition.”,具体错误信息:

Fetch error
response status is 400 /v3/api-docs

问题原因及解决方法

核心问题

@ParameterObject与@RequestBody注解同时标注在同一个参数上,两者功能冲突:

  • @ParameterObject用于将URL查询参数、表单参数绑定到对象
  • @RequestBody用于接收JSON格式的请求体
    同时使用会导致springdoc生成OpenAPI文档时逻辑冲突,触发400错误。

解决步骤

  1. 移除冲突注解:删除testRequest参数上的@ParameterObject,修改后的方法签名:
public ResponseEntity<Object> test(@RequestBody @Valid TestRequest testRequest, BindingResult bindingResult) {
    ...
}
  1. 校验实体类配置:确保TestRequest类的JSR-380校验注解(如@NotNull、@Size)配置正确,避免校验逻辑异常影响文档生成。
  2. 多参数场景处理:如果需要同时接收请求体和查询参数,应拆分参数:一个用@RequestBody接收请求体对象,另一个用@ParameterObject接收查询参数对象,不要混在同一个参数上。

内容的提问来源于stack exchange,提问作者bartex9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 16:50:20