Swagger 为继承With泛型生成springdoc openapi规范
我有一个Spring Boot(kotlin)项目,我使用springdoc openapi生成openapi 3规范。我的数据模型如下所示:Swagger 为继承With泛型生成springdoc openapi规范,swagger,openapi,springfox,springdoc,Swagger,Openapi,Springfox,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>
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>()
这里的问题是,我的控制器可以返回狗食
或猫食
,这是在返回类型中指定的。我希望生成的模式是:
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>()
@Schema(
type=“object”,
title=“食品”,
子类型=[CatFood::class,DogFood::class]
)
公开课食物
猫粮类:食品()
食品类:食品
如果您需要使用其中一个进行响应,则必须添加@Response:
@GetMapping("/test")
@ApiResponse(content = [Content(mediaType = "*/*", schema = Schema(oneOf = [Food::class, CatFood::class,DogFood::class]))])
fun test(): Food<out Animal> = DogFood()
@GetMapping(“/test”)
@ApiResponse(content=[content(mediaType=“*/*”,schema=schema(oneOf=[Food::class,CatFood::class,DogFood::class]))
乐趣测试():食物=狗粮()
我在使用带有嵌套属性继承的OpenApi时遇到问题
我使用JsonSubtype注释和泛型作为解决方法
data class AnimalResponse<FoodResponse>(
val id: UUID,
val eats: FoodResponse
)
@JsonSubTypes(value = [
JsonSubTypes.Type(
value = CatFoodResponse::class,
name = "CAT_FOOD"
), JsonSubTypes.Type(
value = DogFoodResponse::class,
name = "DOG_FOOD"
)])
interface FoodResponse
数据类动物响应(
valid:UUID,
瓦尔吃:食物反应
)
@JsonSubTypes(值=[
JsonSubTypes.Type(
值=CatFoodResponse::类,
name=“猫粮”
),JsonSubTypes.Type(
value=DogFoodResponse::class,
name=“狗粮”
)])
接口食物响应
这将在AnimalResponse模式中显示所有类型的食物响应
@GetMapping("/test")
@ApiResponse(content = [Content(mediaType = "*/*", schema = Schema(oneOf = [Food::class, CatFood::class,DogFood::class]))])
fun test(): Food<out Animal> = DogFood()
data class AnimalResponse<FoodResponse>(
val id: UUID,
val eats: FoodResponse
)
@JsonSubTypes(value = [
JsonSubTypes.Type(
value = CatFoodResponse::class,
name = "CAT_FOOD"
), JsonSubTypes.Type(
value = DogFoodResponse::class,
name = "DOG_FOOD"
)])
interface FoodResponse