gpt4 book ai didi

swagger - springdoc-openapi 规范生成与泛型继承

转载 作者:行者123 更新时间:2023-12-03 23:20:53 121 4
gpt4 key购买 nike

我有一个 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>()

和一个像这样的简单 Controller :
@GetMapping("/test")
fun test(): Food<out Animal> = DogFood()

生成的 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


这里的问题是我的 Controller 可以返回 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

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

最佳答案

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

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

如果您需要使用 oneOf 进行响应,则必须添加 @Response:
@GetMapping("/test")
@ApiResponse(content = [Content(mediaType = "*/*", schema = Schema(oneOf = [Food::class, CatFood::class,DogFood::class]))])
fun test(): Food<out Animal> = DogFood()

关于swagger - springdoc-openapi 规范生成与泛型继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59574788/

121 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com