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

如何为不同接口自定义Swagger模型示例且无需手动编写?

问题:Swagger接口自定义模型示例无需手动编写的实现方案

现有一个带有Swagger注解的Car模型类,控制器中有两个返回Car对象的接口getRedCar和getBlueCar。当前配置下,getRedCar的响应示例符合预期(颜色为red),但getBlueCar的响应示例颜色仍显示为red,不符合需求。如果手动在接口中编写JSON示例,当Car类属性增减时,Swagger文档无法自动同步更新。需要实现无需手动编写示例,就能基于接口自定义模型示例的方案。

现有代码

Car模型类

class Car {

    @Schema(name = "Brand of car", example = "Tesla")
    public String brand;

    @Schema(name = "Color of car", example = "red")
    public String color;
}

控制器接口

@ApiResponse(responseCode = "200", description = "Ok", content = 
      { @Content(mediaType = "application/json", schema = 
        @Schema(implementation = Car.class)) })
public Car getRedCar() {...}

@ApiResponse(responseCode = "200", description = "Ok", content = 
      { @Content(mediaType = "application/json", schema = 
        @Schema(implementation = Car.class)) })
public Car getBlueCar() {...}

解决方案

可以通过在接口的@Schema注解中使用properties属性,覆盖模型类中特定字段的示例值。这种方式既保留模型类的基础定义,又能为不同接口自定义专属示例,同时保证模型属性变更时文档自动更新。

修改后的控制器接口代码

// getRedCar接口保持原有配置
@ApiResponse(responseCode = "200", description = "Ok", content = 
      { @Content(mediaType = "application/json", schema = 
        @Schema(implementation = Car.class)) })
public Car getRedCar() {...}

// 修改getBlueCar接口的@Schema注解,覆盖color字段的示例
@ApiResponse(responseCode = "200", description = "Ok", content = 
      { @Content(mediaType = "application/json", schema = 
        @Schema(implementation = Car.class,
                properties = {
                    @SchemaProperty(name = "color", example = "blue")
                })) })
public Car getBlueCar() {...}

原理说明

  • @Schema(implementation = Car.class)指定响应模型为Car类,自动继承模型类所有字段的定义与默认示例。
  • properties属性用于精准覆盖特定字段的配置,这里仅修改color字段的example值为"blue",其余字段(如brand)仍沿用模型类的示例设置。
  • 当Car类新增或删除属性时,Swagger文档会自动同步这些变更,无需手动调整接口的注解配置。

若需更复杂的自定义逻辑(如多字段批量覆盖、动态生成示例),可通过实现SchemaCustomizer接口全局或针对特定接口调整模型示例,但上述方法已能满足大多数常规场景需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:15:40