【发布时间】:2020-06-14 23:51:53
【问题描述】:
我在控制器中使用泛型。
例如,从某些端点我返回 Response<News> 和 Response<Tag>。
嗯,Swagger 会自动生成这部分 yaml
responses:
200:
description: default response
content:
application/json:
schema:
$ref: '#/components/schemas/ResponseNews'
和
responses:
200:
description: default response
content:
application/json:
schema:
$ref: '#/components/schemas/ResponseTags'
这是我在 Java 中的响应实体。
public class Response<T> {
private List<T> data;
private Boolean moreDataExists;
}
这就是 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
嗯,这几乎是重复的代码。我想避免它,只在我的端点描述中使用响应,并明确地向我的用户展示我使用泛型。
类似的东西:
responses:
200:
description: default response
content:
application/json:
schema:
$ref: '#/components/schemas/Response'
contains:
$ref: '#/components/schemas/News'
我什至无需 Swagger 就可以手动完成。有没有办法做到这一点,也许使用继承或多态?
【问题讨论】:
-
你知道你可以使用默认的 Springboot ResponseEntity 并返回一个
ResponseEntity<List<News>>....moreDataExists看起来更像是一个端点特定的变量 -
如果您想手动更改,如果有区分您返回的响应的内容,您可以使用discriminator。您可以在 Redoc 中检查此 example 以了解它是如何解释的。更改“petType”值并注意字段的变化。
标签: java swagger openapi springdoc