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

如何使用注解在Swagger Schema中为不同类指定枚举的特定取值

有可行的实现方案,操作步骤如下:

  • 确认你使用的Swagger版本引入对应依赖,主流方案分为OpenAPI3(SpringDoc实现,适配SpringBoot2/3)和Swagger2(SpringFox实现,适配较低版本SpringBoot)
  • 给AnimalType枚举类添加Swagger注解,让框架自动识别所有枚举可选值
  • 给Cat、Dog类的type字段单独添加注解,指定必填状态、示例值,绑定枚举类型

OpenAPI3(SpringDoc)适配代码

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Animal {
    protected String name;
    protected Integer age;

    @Schema(description = "动物类型枚举")
    public enum AnimalType{
        ANGRY,
        FUNNY
    }
}

@Getter
@Setter
public class Cat extends Animal{
    @Schema(required = true, example = "ANGRY", implementation = AnimalType.class)
    private AnimalType type=AnimalType.ANGRY;
}

@Getter
@Setter
public class Dog extends Animal{
    @Schema(required = true, example = "FUNNY", implementation = AnimalType.class)
    private AnimalType type=AnimalType.FUNNY;
}

Swagger2(SpringFox)适配代码

把上述代码的@Schema注解替换为@ApiModelProperty即可:

import io.swagger.annotations.ApiModelProperty;

// Dog类示例
@Getter
@Setter
public class Dog extends Animal{
    @ApiModelProperty(required = true, example = "FUNNY", allowableValues = "ANGRY,FUNNY")
    private AnimalType type=AnimalType.FUNNY;
}

配置完成后启动项目,打开Swagger UI即可生成符合要求的文档:type字段标记为必填项,类型显示为AnimalType对应字符串,示例值对应每个子类的默认取值,同时会列出所有枚举可选值。

注:你示例文档里的FANNY应为拼写错误,如果确实需要显示该值,直接修改注解里的example属性为FANNY即可。

内容的提问来源于stack exchange,提问作者Алексеев станислав

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:54:00