如何使用java注释创建多个404响应(或者更广泛地说,创建多个相同的HTTP代码响应)。
我试过:
@ApiResponse(
responseCode = "404",
description = "Not Found 1"
)
@ApiResponse(
responseCode = "404",
description = "Not Found 2"
)同时也是多重@Content
@ApiResponse(
responseCode = "404",
content = {
@Content(schema = @Schema(name = "404-1", description = "404-1")),
@Content(schema = @Schema(name = "404-2", description = "404-2"))
}
)唯一能得到类似于多重的东西的方法是使用@ExampleObject[]
@ApiResponse(
responseCode = "404",
content = @Content(
mediaType = "application/json",
examples = {
@ExampleObject(name = "404-1", description = "Not Found 1 desc"),
@ExampleObject(name = "404-2", description = "Not Found 2 desc")
}
)
)这是,而不是理想的,因为它需要人与人的交互来查看所有这些,只是不需要;我们的期望是:
- 200
- 404 Description 1
- 404 Description 2
- 404 Description 3甚至更好:
- 200
- 404 Description 1
Description 2
Description 3我使用的是springdoc和下面的dep:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.4.3</version>
</dependency>发布于 2020-08-09 17:55:14
通过设计,而不是springdoc,而是OpenAPI规范,所有的响应都存储在扩展ApiResponses的LinkedHashMap类型中。
每个HTTP代码,对于一个操作只能分配一个ApiResponse对象。
使用示例是一个很好的方法。如果您的多个404响应具有不同的结构,您可以使用以下一个:
@RestController
public class HelloController {
@GetMapping("/hello")
@ApiResponses({
@ApiResponse(responseCode = "200"),
@ApiResponse(description = "Not found", responseCode = "404",
content = @Content(mediaType = "application/json", schema = @Schema(oneOf = {
Foo.class, Bar.class }))) })
String hello() {
return null;
}
@Schema(description = "this is bar")
class Bar {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
@Schema(description = "this is foo")
class Foo {
private String foo;
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
}发布于 2020-08-10 14:08:42
我只是在需要新行的描述中添加一个HTML <br/>标记,从而解决了我的问题:
@Operation(
responses = {
@ApiResponse(responseCode = "404", content = @Content,
description =
"This is potential 404 #1 <br/>" +
"This is potential 404 #2"
)
}
)

或者,
您可以创建一个注释,使其更具可读性,例如,类似于@ApiResponse404的内容,并通过OperationCustomizer将其添加到操作中。
@Override
public Operation customize(Operation operation, HandlerMethod handlerMethod) {
ApiResponse404 notFounds = handlerMethod.getMethodAnnotation(ApiResponse404.class);
if (notFounds != null)
operation.getResponses()
.addApiResponse("404", new ApiResponse()
.description(String.join("<br/>", notFounds.value()))
);
return operation;
}当然,您必须考虑到@Content,您可以轻松地将它添加到注释中,但是我不需要它--我的场景,我只需要描述。
然后,在控制器中可以使用注释:
@GetMapping("/helloworld")
@ApiResponse404({"This is potential 404 #1", "This is potential 404 #2"})
String getHelloWorld() {
return "Hello. World.";
}https://stackoverflow.com/questions/63269298
复制相似问题