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

Spring Boot Open API 3.0:如何无需手动写JSON展示自定义示例

解决方案

方法1:DTO类上定义全局复用示例

如果该错误DTO的示例可在多接口复用,直接在ErpResponseBodyDTO上添加@Schema注解指定示例:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(example = "{\"code\": 123, \"message\": \"Error Message\"}")
public class ErpResponseBodyDTO{
  private Long code;
  private String message;
}

之后在@ApiResponse中指定响应类型为该DTO,Swagger UI会自动读取DTO上的示例:

@ApiResponse(responseCode = "401",
                description = "Something is required.",
                content = {
                        @Content(mediaType = "application/json",
                                schema = @Schema(implementation = ErpResponseBodyDTO.class)
                        )
                })
public abstract ResponseEntity<Mono<Object>> queryLegacy(String query);

优势:示例定义一次,所有引用该DTO的接口自动复用,无需重复配置。

方法2:通过Spring组件灵活定义多场景示例

如果需要为不同接口的同一错误码配置不同示例,可借助Spring Bean和OpenAPI组件实现:

  1. 创建示例提供类:
@Component
public class ErrorExamples {
    // 针对401场景的示例
    public ErpResponseBodyDTO unauthorizedExample() {
        return new ErpResponseBodyDTO(123, "Something is required.");
    }

    // 可添加其他错误场景的示例方法
    public ErpResponseBodyDTO forbiddenExample() {
        return new ErpResponseBodyDTO(456, "Access denied.");
    }
}
  1. 配置SpringDoc注册示例组件:
@Configuration
public class SpringDocConfig {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Bean
    public OpenAPI customOpenAPI(ErrorExamples errorExamples) throws JsonProcessingException {
        return new OpenAPI()
                .components(new Components()
                        // 注册401示例
                        .addExamples("UnauthorizedExample",
                                new Example().value(OBJECT_MAPPER.writeValueAsString(errorExamples.unauthorizedExample()))
                        )
                        // 可注册其他示例
                        .addExamples("ForbiddenExample",
                                new Example().value(OBJECT_MAPPER.writeValueAsString(errorExamples.forbiddenExample()))
                        )
                );
    }
}
  1. 在接口注解中引用示例:
@ApiResponse(responseCode = "401",
                description = "Something is required.",
                content = {
                        @Content(mediaType = "application/json",
                                examples = {
                                    @Example(
                                            name = "UnauthorizedExample",
                                            value = @ExampleObject(ref = "#/components/examples/UnauthorizedExample")
                                    )
                                },
                                schema = @Schema(implementation = ErpResponseBodyDTO.class)
                        )
                })
public abstract ResponseEntity<Mono<Object>> queryLegacy(String query);

优势:示例集中管理,支持多场景自定义,无需手动编写JSON。

方法3:工具类序列化对象快速实现

如果不想配置全局组件,可通过工具类将对象序列化为JSON字符串,直接在注解中使用:

  1. 编写JSON工具类:
public class JsonUtils {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static String toJson(Object obj) {
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize object to JSON", e);
        }
    }
}
  1. 在接口注解中使用:
@ApiResponse(responseCode = "401",
                description = "Something is required.",
                content = {
                        @Content(mediaType = "application/json",
                                examples = {
                                    @ExampleObject(
                                            name = "UnauthorizedExample",
                                            value = JsonUtils.toJson(new ErpResponseBodyDTO(123, "Error Message"))
                                    )
                                },
                                schema = @Schema(implementation = ErpResponseBodyDTO.class)
                        )
                })
public abstract ResponseEntity<Mono<Object>> queryLegacy(String query);

优势:快速实现,无需额外配置;缺点:示例硬编码在注解中,无法动态修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:55:01