You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Springfox迁移到Springdoc,@ApiOperation与@ApiResponse的response替代方案

Springfox迁移到springdoc-openapi-ui:替换@ApiOperation(response)和@ApiResponse(response)

核心替换方案

springdoc-openapi遵循OpenAPI 3规范,不再用response属性指定响应体类型,而是通过@Content配合@Schema来定义:

  1. 替换@ApiOperation(response = Example.class)
    移除@Operation中的response属性,在@ApiResponses里为200状态码的@ApiResponse添加content属性,用@Schema明确响应体类型。

  2. 替换@ApiResponse(response = ErrorResponse.class)
    把每个错误状态码的@ApiResponse里的response属性,替换为content = @Content(schema = @Schema(implementation = ErrorResponse.class))。

修改后的完整代码

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.http.MediaType;

@Operation(
        summary = "sample summary",
        description = "sample description")
@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "Successful", 
                     content = @Content(schema = @Schema(implementation = Example.class))),
        @ApiResponse(responseCode = "400", description = "Bad Request", 
                     content = @Content(schema = @Schema(implementation = ErrorResponse.class))),
        @ApiResponse(responseCode = "401", description = "Not Authorized", 
                     content = @Content(schema = @Schema(implementation = ErrorResponse.class))),
        @ApiResponse(responseCode = "403", description = "Forbidden", 
                     content = @Content(schema = @Schema(implementation = ErrorResponse.class))),
        @ApiResponse(responseCode = "404", description = "Not Found", 
                     content = @Content(schema = @Schema(implementation = ErrorResponse.class)))})
@PostMapping(value = {"/sampleEndpoint"}, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)

补充说明

  • 如果接口方法的返回值本身就是Example.class,springdoc会自动识别200的响应体类型,此时可省略200的@Content配置,但显式声明能让接口文档更清晰。
  • 务必确保导入的是springdoc对应的注解包(io.swagger.v3.oas.annotations下的类),不要和Springfox的注解混淆。

内容的提问来源于stack exchange,提问作者bocodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:55:21