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

Swagger v3请求体默认值不生效,自定义默认值失败求助

解决Swagger v3自定义请求体默认示例不生效的问题

针对你遇到的Swagger v3无法显示自定义请求体默认值的问题,提供以下几种可行方案:

方案1:在实体类字段上直接配置@Schema示例

将示例值直接标注在实体类的字段上,Swagger会自动读取这些值作为请求体的默认示例:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Example{
    @Schema(example = "0")
    private Long id;
    @Schema(example = "Default Title")
    private String title;
}

这种方式无需在接口层额外配置,示例会自动关联到所有使用该实体类的请求体中。

方案2:在接口层用@ExampleObject配置完整请求体示例

如果需要在特定接口单独定义请求体示例,不要在@Schema中设置example,而是使用@Content的examples属性:

@PutMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
@ApiResponse(responseCode = "200", description = "test")
@Operation(
        summary = "test",
        requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
        content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(name = "默认示例", value = SwaggerConstants.EXAMPLE_DEFAULT_VALUES)
        )
))
public Example uploadExample(
        @PathVariable("id") Long id,
        @RequestBody() Example example) {
    return exampleService.uploadExample(id, example);
}

@ExampleObject用于定义完整的请求体JSON示例,Swagger UI会优先显示这里配置的内容。

方案3:检查依赖版本兼容性

确保你使用的springdoc-openapi依赖版本与Spring Boot版本匹配:

  • Spring Boot 2.x:使用springdoc-openapi-ui依赖(推荐版本如1.6.14)
  • Spring Boot 3.x:使用springdoc-openapi-starter-webmvc-ui依赖(推荐版本如2.2.0)
    版本不兼容可能导致注解无法被正确解析。

原配置无效的原因

你之前在@Schema中设置的example属性,是用于定义Schema本身的元数据示例,而非请求体的完整示例。Swagger v3在处理请求体时,会优先读取@Content中的examples配置,或是实体类字段上的@Schema示例,而非你原来的配置方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:22:55