SpringDoc+Swagger YAML生成代码:错误响应Schema显示异常问题
问题背景
使用Swagger YAML生成Spring代码后,Swagger UI中400、500等错误状态码的响应复用了成功状态码的Schema,而非显示为无内容。springdoc官方文档明确可通过@Content(schema = @Schema(hidden = true))定义无内容响应,但生成的代码无法直接修改。
当前YAML配置片段:
400: description: Requisição inválida content: { } 401: description: Falha na autenticação content: { } 500: description: Erro no sistema content: { }
生成的代码中错误响应未包含content注解:
@ApiResponse(responseCode = "400", description = "Requisição inválida")
解决方案
方案1:调整Swagger YAML配置,明确标记隐藏Schema
修改YAML中错误响应的content字段,指定媒体类型并设置schema.hidden为true:
400: description: Requisição inválida content: application/json: schema: hidden: true 401: description: Falha na autenticação content: application/json: schema: hidden: true 500: description: Erro no sistema content: application/json: schema: hidden: true
重新生成代码后,Codegen会自动为这些响应添加content = @Content(schema = @Schema(hidden = true))注解。
方案2:配置Swagger Codegen启用springdoc支持
如果使用Maven插件生成代码,在插件配置中添加springdoc和defaultResponseContent参数:
<plugin> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>3.0.34</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/swagger.yaml</inputSpec> <language>spring</language> <configOptions> <springdoc>true</springdoc> <!-- 启用springdoc注解适配 --> <defaultResponseContent>false</defaultResponseContent> <!-- 为空响应不生成默认content --> <interfaceOnly>true</interfaceOnly> <!-- 仅生成接口类(按需配置) --> </configOptions> </configuration> </execution> </executions> </plugin>
如果使用Codegen CLI,添加对应参数执行生成:
swagger-codegen generate -i swagger.yaml -l spring --springdoc true --default-response-content false
启用springdoc参数后,Codegen会按照springdoc规范生成注解,空content的响应会自动带上目标注解。
方案3:自定义Codegen模板(进阶)
若上述方案无法满足需求,可自定义Codegen的模板逻辑:
- 从Swagger Codegen仓库获取Spring模板的
api.mustache文件 - 修改模板中生成
@ApiResponse的逻辑,当响应的content为空时,自动追加content = @Content(schema = @Schema(hidden = true)) - 在Codegen配置中指定自定义模板路径:
<configOptions> <templateDirectory>${project.basedir}/src/main/resources/codegen-templates</templateDirectory> </configOptions>
验证效果
重新生成代码后,错误响应的注解应变为:
@ApiResponse(responseCode = "400", description = "Requisição inválida", content = @Content(schema = @Schema(hidden = true)))
此时Swagger UI中错误状态码的响应会显示为无内容,不再复用成功响应的Schema。
内容的提问来源于stack exchange,提问作者Borsoi
相关产品推荐
相关产品推荐

