Swagger 中 @ApiResponse 注解的可重用性

Dol*_*ava 5 swagger swagger-2.0 openapi

我正在使用 Swagger 注释来记录非 Spring 上下文中的 API。我发现 400、401 和 404 的响应文档是可以重复使用的。因为记录每个响应代码大约需要 8 行,如下所示。

    @Operation(
            summary = "getDetails",
            description = "someDescription",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "Found",
                            content = @Content(mediaType = "application/json",
                                    schema =  @Schema(
                                            name = "Response for success")
                            )
                    ),
                    @ApiResponse(
                            responseCode = "400",
                            description = "Validation failure on inputs.",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            name = "Response For Bad Request")
                            )
                    ),
                    @ApiResponse(
                            responseCode = "404",
                            description = "Not found",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            name = "Response For Not Found Request")
                            )

                    ),
                    @ApiResponse(
                            responseCode = "401",
                            description = "Unauthorized",
                            content = @Content(
                                    mediaType = "application/json",
                                    schema = @Schema(
                                            name = "Response For Unauthorized")
                            )
                    )
            }
    )
Run Code Online (Sandbox Code Playgroud)

我打算防止每个可重用 API 响应的行变得臃肿。我更喜欢下面这样的东西

  @Operation(
            summary = "getDetails",
            description = "someDescription",
            responses = {
                   @ApiResponse(
                            responseCode = "200",
                            description = "Found",
                            content = @Content(mediaType = "application/json",
                                    schema =  @Schema(
                                            name = "Response for success")
                            )
                    ),
                    SomeStaticClass.getBadResponseDesc(),
                    SomeStaticClass.getUnauthorizedResponseDesc()
}
Run Code Online (Sandbox Code Playgroud)

java 8 有什么办法可以实现这一点吗?

Jam*_*der 0

是的,用在物体globalResponseMessageDocket。有关其使用示例,请参阅springfox 文档中的第 22 点。@ApiResponse我使用这种方法从代码中删除了很多注释。