gpt4 book ai didi

spring - swagger结合一些重复的注释

转载 作者:行者123 更新时间:2023-12-02 08:15:25 26 4
gpt4 key购买 nike

我在每个方法中使用.useDefaultResponseMessages(false)

@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = Order.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
public Order getOrder......

@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = User.class),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
public User getUser......

我可以合并一些重复的注释吗?(默认)

最佳答案

1。在 Controller 级别使用 @ApiResponses

在 Controller 级别定义通用响应,而不是为每个方法重复它们:

@ApiResponses({
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
@Controller
public class UserOrderController {
@ApiResponse(code = 200, message = "Success", response = Order.class)
@GetMapping("/order")
public Order getOrder() { /*......*/ }

@ApiResponse(code = 200, message = "Success", response = User.class)
@GetMapping("/user")
public User getUser() { /*......*/ }
}

实际上,如果 @ApiResponse 与方法返回类型匹配,则不需要在 @ApiResponse 中指定 response 类型。因此,在提供的示例中,我们可以为每个 Controller 定义一次所有响应,以减少重复注释。

2。使用自定义注释

通过定义自定义注释在 Controller 之间共享重复注释:

/**
* A convenient meta-annotation for Swagger API responses.
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@ApiResponses({
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Forbidden"),
@ApiResponse(code = 404, message = "Not Found"),
@ApiResponse(code = 500, message = "Failure")})
@interface DefaultApiResponses {}

然后像这样使用它:

@DefaultApiResponses
@Controller
public class UserOrderController {
@GetMapping("/order")
public Order getOrder() { /*......*/ }

@GetMapping("/user")
public User getUser() { /*......*/ }
}

此答案中提供的源代码可在 Github 上找到。 .

关于spring - swagger结合一些重复的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46324478/

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