nsa*_*rli 5 java swagger swagger-ui spring-boot openapi
我正在尝试使用 Swagger UI 创建和部署我的文档以及我使用 Spring Boot 编写的 API。我知道 Swagger 提供了一些注释来帮助在实际控制器类中编写文档,但我在尝试让它们执行我需要的操作时遇到了麻烦。
我的问题是我有一个通用的 DTO 类,每次调用我的 API 都会返回该类。此 DTO 有一个contents用于通用对象的字段。如果我直接使用这些对象,我知道我可以使用类似的东西
@ApiResponse(responseCode = "200", description = "Customer found",
content = @Content(
schema = @Schema(implementation = Customer.class)))
Run Code Online (Sandbox Code Playgroud)
以便给出对象的 JSON 表示形式的规范。但是,因为我将所有内容包装在特定的ResponseDTO类中,所以我需要一种方法来指定字段contents应该是什么样子,并且我不确定可以使用哪些注释来完成此任务。我觉得肯定应该有类似的东西
@ApiResponse(responseCode = "200", description = "Customer found",
content = @Content(
schema = @Schema(implementation = DTO.class,
fields = { "contents" = @Schema(implementation = Customer.class)})))
Run Code Online (Sandbox Code Playgroud)
或类似的东西。我一直无法找到如何真正实现这一目标的解释。我的直觉表明应该有一种方法可以将模式放入模式中,但也许还有另一种我没有考虑过的解决方案。任何帮助或寻找方向将不胜感激。提前致谢。
我知道这篇文章很旧,但无论如何我都会发布这篇文章,以防有人遇到类似的问题。
我还必须返回一个对象列表,其中这些对象的字段之一必须根据某些请求参数进行更改。为了在 Swagger 中记录这些子模式(如您所说的模式内的模式),您可以使用注释的oneOf属性@Schema并提供通用类的列表。
这是一个例子:
Customer.java:
public class Customer {
// Some other fields...
@Schema(
description = "List of generic contents inside Customer",
oneOf = {Bar.class, Foo.class})
private List<IContent> contents;
}
Run Code Online (Sandbox Code Playgroud)
IContent.java只是一些接口(或者它可以是泛型类的任何超类):
public interface IContent extends Serializable { }
Run Code Online (Sandbox Code Playgroud)
假设Foo.javaandBar.java是两个通用类:
public class Bar implements IContent {
@Schema(description = "Some dummy name field inside Bar")
private String dummyName;
@Schema(description = "Some dummy number field inside Bar")
private Integer dummyNo;
}
public class Foo implements IContent {
@Schema(description = "Some dummy ID field inside Foo")
private Long contentID;
}
Run Code Online (Sandbox Code Playgroud)
如果您有与记录通用对象列表不同的需求,另请参阅其他类型的子模式属性的allOf 和 anyOf 属性。
看起来你正在做相反的事情。我通过使用http://swagger.io上的编辑器创建指定 API 的 .yaml 文件来完成此操作
\n这样,您的 .yaml 文件可以为每种数据类型指定不同的 DTO,并且您可以为每个 API 指定它返回的类型。
\n另外,您不会发布您的 ResponseDTO 类的样子。我希望你已经概括了它:
\npublic class ResponseDTO<T> {\n public T getData() { \xe2\x80\xa6 }\n \xe2\x80\xa6\n}\nRun Code Online (Sandbox Code Playgroud)\n但我不确定拥有这样的自己的对象是否是一个好主意。在我过去的一些项目中,我们为每种数据类型定义了一个单独的响应类,但它们都做同样的事情!您的框架可能已经为您编写了一个这样的类。
\n您正在使用 Spring Boot,这也是我使用的。对于 Spring,该类是org.springframework.http.ResponseEntity. (其他框架可能有自己的版本。)并且它是通用的,因此您可以向其中添加任何数据类型的内容。但 Swagger 要求您指定添加内容的类型,而不是ResponseEntity类本身。您的 ResponseDTO 类妨碍了您。
因此,如果您想返回 CustomProduct 类型,您的 swagger 生成的注释将指定 CustomProduct.class,并且您的服务方法将如下所示:
\n\xe2\x80\xa6 (more annotations)\n@ApiResponses(value = { \n @ApiResponse(code=200, message="Found", response=CustomProduct.class)\n})\npublic ResonseEntity<CustomProduct> getCustomProduct(\xe2\x80\xa6) {\n CustomProduct myCustomProduct = retrieveCustomProduct(\xe2\x80\xa6);\n return new ResponseEntity<>(myCustomProduct, HTTPStatus.OK);\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
24119 次 |
| 最近记录: |