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

如何在SpringDoc中展示BadRequestResponse的结构化示例响应?

解决SpringDoc生成Swagger文档中Map类型响应示例不符合预期的问题

针对你遇到的BadRequestResponse类中Map<String,List<String>>类型字段生成示例不直观的问题,提供以下几种配置方案:

方案1:在响应类上直接指定完整示例

通过@Schema注解的example属性,给BadRequestResponse类设置完整的JSON响应示例,所有引用该类的接口都会统一使用这个示例。

修改后的类代码:

@Data
@RequiredArgsConstructor
@AllArgsConstructor
@Builder
@Schema(example = """
{
    "message": "Validation Failed",
    "failed_validation_attributes": {
        "lastName": [
            "Second Name Should Not Be Null or Empty"
        ],
        "firstName": [
            "First Name Should Not Be Null or Empty"
        ]
    }
}
""")
public class BadRequestResponse {

    @Schema(type = "string", example = "Validation Failed")
    private String message;

    @Schema(description = "存储各属性的验证失败原因")
    private Map<String,List<String>> failed_validation_attributes;
}

注:Java 15及以上支持文本块语法("""包裹),低版本可使用转义字符串替代。

方案2:针对单个接口定制响应示例

如果需要给特定接口单独设置400响应示例,可以在Controller方法的@ApiResponse中通过@ExampleObject指定:

@Operation(summary = "示例业务接口")
@ApiResponses(value = {
    @ApiResponse(responseCode = "400", description = "请求验证失败",
        content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE,
            examples = @ExampleObject(value = """
{
    "message": "Validation Failed",
    "failed_validation_attributes": {
        "lastName": [
            "Second Name Should Not Be Null or Empty"
        ],
        "firstName": [
            "First Name Should Not Be Null or Empty"
        ]
    }
}
""")))
})
@PostMapping("/your-api-path")
public ResponseEntity<?> yourApiMethod(@Valid @RequestBody YourRequestDto request) {
    // 接口业务逻辑
    return ResponseEntity.ok().build();
}

方案3:通过配置类全局设置Schema示例

如果需要统一管理所有Swagger Schema的示例,可以创建SpringDoc配置类,在其中自定义BadRequestResponse的示例:

@Configuration
public class SpringDocConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components()
                        .schemas(Map.of(
                                "BadRequestResponse", new Schema<>()
                                        .example(Map.of(
                                                "message", "Validation Failed",
                                                "failed_validation_attributes", Map.of(
                                                        "lastName", List.of("Second Name Should Not Be Null or Empty"),
                                                        "firstName", List.of("First Name Should Not Be Null or Empty")
                                                )
                                        ))
                        )));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:13:14