首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在由Java代码生成的Swagger规范中创建可重用枚举?

如何在由Java代码生成的Swagger规范中创建可重用枚举?
EN

Stack Overflow用户
提问于 2019-07-17 15:48:11
回答 2查看 3.9K关注 0票数 5

我正在尝试为我的OpenAPI代码生成OpenAPI(Version3.0.1)规范。为了实现这一点,我使用Swagger注释(Version2.0.8)和Swagger插件。

我对埃努姆有意见。比如说,我有两种方法返回完全相同的Enum。在OpenAPI规范中,我希望在两个API操作中都有这个Enum和$ref链接的单一模式定义。但是,我在每个API操作中都复制了Enum定义。如何避免这种复制而不手动编辑规范文件?

下面是Java代码,其中两个方法返回相同的Enum:

代码语言:javascript
复制
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/properties")
@Produces("application/json")
public class TestService {
    @GET
    @Path("/enum1")
    @Operation
    @ApiResponses({
        @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
    })
    public Color getColor1() {
        throw new UnsupportedOperationException();
    }

    @GET
    @Path("/enum2")
    @Operation
    @ApiResponses({
        @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
    })
    public Color getColor2() {
        throw new UnsupportedOperationException();
    }

    public enum Color {
        RED,

        GREEN,

        BLUE
    }
}

这里是我想要得到的规范:

代码语言:javascript
复制
openapi: 3.0.1
components:
    schemas:
        Color:
            type: string
            enum:
                - RED
                - GREEN
                - BLUE
paths:
  /properties/enum2:
    get:
      operationId: getColor2
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Color'
  /properties/enum1:
    get:
      operationId: getColor1
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Color'

下面是我得到的说明:

代码语言:javascript
复制
openapi: 3.0.1
paths:
  /properties/enum2:
    get:
      operationId: getColor2
      responses:
        200:
          content:
            application/json:
              schema:
                type: string
                enum:
                - RED
                - GREEN
                - BLUE
  /properties/enum1:
    get:
      operationId: getColor1
      responses:
        200:
          content:
            application/json:
              schema:
                type: string
                enum:
                - RED
                - GREEN
                - BLUE
EN

回答 2

Stack Overflow用户

发布于 2021-02-04 10:36:18

我在kotlin,但我成功地将(相对较新的) @Schema(enumAsRef = true)添加到枚举类中。

代码语言:javascript
复制
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/properties")
@Produces("application/json")
public class TestService {
    @GET
    @Path("/enum1")
    @Operation
    @ApiResponses({
        @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
    })
    public Color getColor1() {
        throw new UnsupportedOperationException();
    }

    @GET
    @Path("/enum2")
    @Operation
    @ApiResponses({
        @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = Color.class)))
    })
    public Color getColor2() {
        throw new UnsupportedOperationException();
    }

    @Schema(enumAsRef = true) // THIS MAKES ENUM REF
    public enum Color {
        RED,

        GREEN,

        BLUE
    }
}
票数 4
EN

Stack Overflow用户

发布于 2021-07-20 14:52:50

我在Dropwizard应用程序中也面临着同样的问题。

我的模特是这样的:

代码语言:javascript
复制
public class Model {

  @Schema(name = "fields")
  @Default
  @NotNull
  private Set<CustomEnum> fields = Collections.emptySet();

  @Schema(name = "patches")
  @Default
  @NotNull
  private Set<CustomEnum> patches = Collections.emptySet();
}

我的心肠:

代码语言:javascript
复制
public enum CustomEnum {
  COMPANY,
  PERSON,
  EMAIL
}

我的做法如下:

首先,将@Schema注释添加到CustomEnum枚举中:

代码语言:javascript
复制
@Schema(ref = "#/components/schemas/CustomEnumItem")
public enum CustomEnum {}

注意,我将引用名更改为CustomEnumItem

其次,我以编程方式注册了模式和swagger配置:

代码语言:javascript
复制
OpenAPI oas =
    new OpenAPI()
        .info(getInfo())
        .addServersItem(new Server().url(baseUrl));

var customEnumItem = new Schema<CustomEnumItem>();
patchKeysItem.setType("string");
patchKeysItem.setEnum(List.of(CustomEnumItem.values()));
oas.getComponents().addSchemas("CustomEnumItem", customEnumItem);

return new SwaggerConfiguration()
    .openAPI(oas)
    .readAllResources(true)
    .prettyPrint(true);

因此,我的swagger.json文件是这样生成的:

  • 模式部分:
代码语言:javascript
复制
  "components" : {
    "schemas" : {
      "PatchKeyItem" : {
        "type" : "string",
        "enum" : [ "COMPANY", "PERSON", "EMAIL"]
      },
  • 示范部分:
代码语言:javascript
复制
"Model" : {
        "required" : [ "fields", "patches"],
        "type" : "object",
        "properties" : {
          "fields" : {
            "uniqueItems" : true,
            "type" : "array",
            "items" : {
              "$ref" : "#/components/schemas/CustomEnumItem"
            }
          },
          "patches" : {
            "uniqueItems" : true,
            "type" : "array",
            "items" : {
              "$ref" : "#/components/schemas/CustomEnumItem"
            }
          },

我生成的客户端代码如下:

代码语言:javascript
复制
public class Model  {

    @JsonProperty("fields")
    private Set<CustomEnumItem> fields;

    @JsonProperty("patches")
    private Set<CustomEnumItem> patches;

在进行此更改之前,我得到了这样的内容(两个枚举而不是一个):

代码语言:javascript
复制
public class Model  {

    @JsonProperty("fields")
    private Set<FieldsEnum> fields;

    @JsonProperty("patches")
    private Set<PatchesEnum> patches;
}

我们可以找到对可重用枚举这里的引用。

同样,正如@david提到的那样,enumAsRef也可以工作,但是您需要使用swagger注释2.1.0。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57079808

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档