springdoc-openapi 使用泛型继承的规范生成

Ved*_*hat 3 swagger springfox openapi springdoc

我有一个 Spring Boot (kotlin) 项目,我使用 springdoc-openapi 来生成 OpenApi 3 规范。我的数据模型如下所示:

open class Animal
data class Cat(val catName: String) : Animal()
data class Dog(val dogName: String) : Animal()

open class Food<T : Animal>
class CatFood : Food<Cat>()
class DogFood : Food<Dog>()
Run Code Online (Sandbox Code Playgroud)

和一个像这样的简单控制器:

@GetMapping("/test")
fun test(): Food<out Animal> = DogFood()
Run Code Online (Sandbox Code Playgroud)

生成的 yaml 是:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8085
paths:
  /test:
    get:
      tags:
      - test-controller
      operationId: test
      responses:
        "200":
          description: default response
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/FoodAnimal'
components:
  schemas:
    FoodAnimal:
      type: object

Run Code Online (Sandbox Code Playgroud)

这里的问题是我的控制器可以返回DogFoodCatFood,并且在返回类型中指定。我希望生成的模式是:

openapi: 3.0.1
info:
  title: OpenAPI definition
  version: v0
servers:
- url: http://localhost:8085
paths:
  /test:
    get:
      tags:
      - test-controller
      operationId: test
      responses:
        "200":
          description: default response
          content:
            '*/*':
              schema:
                oneOf:
                  - $ref: '#/components/schemas/FoodAnimal'
                  - $ref: '#/components/schemas/DogFood'
                  - $ref: '#/components/schemas/CatFood'

components:
  schemas:
    FoodAnimal:
      type: object
    CatFood:
      allOf:
        - $ref: '#/components/schemas/FoodAnimal'
      type: object
    DogFood:
      allOf:
        - $ref: '#/components/schemas/FoodAnimal'
      type: object
Run Code Online (Sandbox Code Playgroud)

有什么方法可以实现这一目标吗?

小智 11

对于继承,你只需要在你的父类上添加@Schema注解:

@Schema(
        type = "object",
        title = "Food",
        subTypes = [CatFood::class, DogFood::class]
)
open class Food<T : Animal>
class CatFood : Food<Cat>()
class DogFood : Food<Dog>()
Run Code Online (Sandbox Code Playgroud)

如果您需要使用 oneOf 进行响应,则必须添加 @Response:

@GetMapping("/test")
@ApiResponse(content = [Content(mediaType = "*/*", schema = Schema(oneOf = [Food::class, CatFood::class,DogFood::class]))])
fun test(): Food<out Animal> = DogFood()
Run Code Online (Sandbox Code Playgroud)