【问题标题】:Why are final fields of a Java DTO hidden in openapi.yml为什么 Java DTO 的最终字段隐藏在 openapi.yml 中
【发布时间】:2023-02-11 08:44:14
【问题描述】:

我正在尝试使用 OpenAPI 在 micronaut 应用程序中从 Java 对象和控制器构建 REST API。我注意到 DTO 的最终成员被排除在生成的描述符之外(在运行的应用程序中为 swagger-ui.html),但我不明白为什么。

使用此代码,所有成员都会出现在 API 中。

public class Overview {
    public String status;
    public Table table1;
    public Table table2;
}
components:
  schemas:
    Overview:
      type: object
      properties:
        status:
          type: string
        table1:
          $ref: '#/components/schemas/Table'
        table2:
          $ref: '#/components/schemas/Table'

对于这个,只有第一个成员是可见的。

public class Overview {
    public String status;
    public final Table table1;
    public final Table table2;
}
components:
  schemas:
    Overview:
      type: object
      properties:
        status:
          type: string

【问题讨论】:

    标签: java openapi


    【解决方案1】:

    在您的案例中,DTO 的最终成员被排除在生成的描述符之外的原因是因为 Micronaut 的 OpenAPI 集成使用 Java Bean Introspection API 从您的 Java 类生成 OpenAPI 规范。根据 Java Bean 标准,出于内省的目的不考虑 final 字段。这意味着最终字段将不会包含在生成的 OpenAPI 规范中。如果您希望最终字段出现在生成的规范中,您可以使用 Jackson 库中的 @JsonProperty 注释来包含它们:

    public class Overview {
        public String status;
        @JsonProperty
        public final Table table1;
        @JsonProperty
        public final Table table2;
    }
    

    这样,最终字段将包含在生成的规范中,并且它们将出现在 swagger-ui.html 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-22
      • 2012-05-17
      • 2011-11-02
      • 2021-11-21
      • 2015-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多