Swagger RequestBody注解description未在Swagger UI显示问题
问题背景
在API接口中使用Swagger OAS3的@Operation注解嵌套@RequestBody配置请求体描述,但Swagger UI的「Request body」区域始终不显示预期的描述文本“Test String for RequestBody Here”。该写法在其他项目中可正常生效,当前项目使用旧版Swagger库,疑似存在版本或依赖问题。
初始代码实现
//@ApiOperation(value = CreateOrUpdate.shortDescription, notes = CreateOrUpdate.detail) @NewSpan @Operation( summary = CreateOrUpdate.shortDescription, description = CreateOrUpdate.detail, requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Test String for RequestBody Here")) // Swagger @PostMapping public UserDTO createOrUpdate(@RequestBody UserDTO dto, @ApiParam(value = CreateOrUpdate.apiParamString) @RequestParam(required = false) boolean skipTrainingUser) { Result result = userService.createOrUpdateCrmUserObject(dto, skipTrainingUser); ... }
已尝试的调整
将Swagger的@RequestBody注解移至方法参数UserDTO dto上方,问题仍未解决:
//@ApiOperation(value = CreateOrUpdate.shortDescription, notes = CreateOrUpdate.detail) @NewSpan @Operation( summary = CreateOrUpdate.shortDescription, description = CreateOrUpdate.detail ) @PostMapping public UserDTO createOrUpdate(@io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Test String for RequestBody Here") @RequestBody UserDTO dto, @Parameter(description = CreateOrUpdate.apiParamString) // @ApiParam(value = CreateOrUpdate.apiParamString) @RequestParam(required = false) boolean skipTrainingUser) { Result result = userService.createOrUpdateCrmUserObject(dto, skipTrainingUser); ... }
排查思路
核对版本兼容性:
旧版Swagger OAS3注解可能存在解析逻辑缺陷,比如@Operation内的requestBody属性无法被正确识别,或者参数上的Spring原生@RequestBody覆盖了Swagger注解的配置。对比正常项目的依赖版本,尝试升级到稳定版(如SpringDoc v1.6.x+、Swagger Core v2.2.x+)。排查依赖冲突:
若项目同时存在Swagger 2.x(@ApiParam等旧注解)和OAS3(@Operation、@Parameter等新注解)依赖,会导致注解解析混乱。用mvn dependency:tree(Maven)或./gradlew dependencies(Gradle)查看依赖树,剔除重复或冲突的Swagger包,确保只保留一套OAS3依赖。修正注解配置细节:
确认使用的是Swagger的@io.swagger.v3.oas.annotations.parameters.RequestBody,而非Spring原生的@org.springframework.web.bind.annotation.RequestBody。部分旧版本需显式指定媒体类型才能渲染描述,可补充配置:@io.swagger.v3.oas.annotations.parameters.RequestBody( description = "Test String for RequestBody Here", content = @Content(mediaType = "application/json") )检查OpenAPI原始文档:
访问项目的/v3/api-docs端点查看生成的OpenAPI JSON/YAML。如果文档中没有请求体描述,说明是注解解析阶段的问题;如果文档中有但UI不显示,需同步升级Swagger UI版本。清理缓存重启服务:
IDE缓存或Spring上下文缓存可能导致注解未重新解析,执行clean构建命令、清理IDE缓存后重启服务,再验证Swagger UI。
内容的提问来源于stack exchange,提问作者jb62

