如何使用 Java 中的泛型制定 OpenAPI 规范

inc*_*ure 5 java swagger openapi springdoc

我在控制器中使用泛型。例如,从某些端点我返回Response<News>Response<Tag>

嗯,Swagger自动生成这部分yaml

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResponseNews'
Run Code Online (Sandbox Code Playgroud)

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ResponseTags'
Run Code Online (Sandbox Code Playgroud)

这是我在 Java 中的 Response 实体。

public class Response<T> {
    private List<T> data;
    private Boolean moreDataExists;
}
Run Code Online (Sandbox Code Playgroud)

这就是 Swagger 生成组件的方式。

ResponseNews:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/News'
        moreDataExists:
          type: boolean

ResponseTags:
      type: object
      properties:
        data:
          type: array
          items:
            $ref: '#/components/schemas/Tags'
        moreDataExists:
          type: boolean
Run Code Online (Sandbox Code Playgroud)

嗯,这几乎是重复的代码。我想避免它,只在我的端点的描述中使用Response,并明确地向我的用户展示我使用泛型。

类似的东西:

responses:
        200:
          description: default response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Response'
                  contains: 
                    $ref: '#/components/schemas/News'

Run Code Online (Sandbox Code Playgroud)

我已经准备好在没有 Swagger 的情况下完成它,只需手动。有没有办法做到这一点,也许使用继承或多态?

bri*_*bro 1

您可以使用 swagger 注释来调整响应,@ApiResponse您可以在其中传递所需的任何自定义对象的架构。