使用 Swagger 注解创建通用组件

Create common component with Swagger annotations

我正在为我的 spring-boot 项目使用 swagger-annotation。

我想return为我的控制器的每个资源制定一个通用的响应代码合同。

在文档中:https://github.com/swagger-api/swagger-core/wiki/annotations#apiresponses-apiresponse 他们谈论@ApiResponses 但我不能将注释放在 class 级别。

这是我所做的:

@Api(value = "Title",
    description = "What this controller is about"
)
@ApiResponses(value = { 
    @ApiResponse(code = 400, message = "Bad stuff from the client"),
    @ApiResponse(code = 404, message = "Item not found") }
    )
public class FooBarController {

      ...

}

但问题是 400 - Bad stuff from the client404 - Item not found 从未显示在生成的文档中。

在swagger的官方文档中我看到了这一段:https://swagger.io/docs/specification/describing-responses/#reuse

问题:如何创建一种带有 java 注释的 "reusable component"?

谢谢

根据文档,您可以在 Docket 级别执行此操作。

.useDefaultResponseMessages(false)
        .globalResponseMessage(RequestMethod.GET,
            newArrayList(new ResponseMessageBuilder()
                .code(400)
                .message("Bad stuff from the client")
                .build()))

https://springfox.github.io/springfox/docs/current/#springfox-spring-mvc-and-spring-boot

更新:

如果您想使用注释路线,您可以创建自己的注释路线并将其放在您的控制器上。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@ApiResponses(value = { 
    @ApiResponse(code = 400, message = "Bad stuff from the client"),
    @ApiResponse(code = 404, message = "Item not found") }
    )
public @interface GlobalApiReponses {
}

那就用吧..

@Api(value = "Title",
    description = "What this controller is about"
)
@GlobalApiReponses
public class FooBarController


多种方法的组合可能也是一个不错的选择。

@Target(ElementType.TYPE) 意味着您可以在 class 级别应用它。您可以使用 ElemenType.METHOD.

对方法执行相同的操作