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

Spring Boot 3.2中OpenAPI/Swagger示例无法显示问题求助

解决Spring Boot 3.2 + SpringDoc OpenAPI中接口响应/参数示例不显示的问题

1. 校验OpenAPI YAML语法格式

确保响应、参数的示例配置层级正确,嵌套在对应媒体类型的content节点下,而非Schema内部(你提到Schema层级示例正常,需区分接口级和Schema级示例的配置位置):

/tests:
  get:
    parameters:
      - name: id
        in: query
        schema:
          type: integer
        examples:
          SampleParam:
            summary: 示例参数
            value: 100
    responses:
      '200':
        description: 成功响应
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/TestResponse'
            examples:
              SampleResponse:
                summary: 示例响应
                value:
                  id: 1
                  name: "测试数据"

若使用单个example而非多示例examples,同样要放在content节点下、与schema同级。

2. 调整SpringDoc配置

在application.yml或application.properties中开启示例渲染相关配置:

springdoc.api-docs.enabled=true
springdoc.swagger-ui.enable=true
springdoc.swagger-ui.default-models-expand-depth=-1 # 避免Schema层级示例覆盖接口级示例
springdoc.swagger-ui.display-request-duration=true

确认springdoc-openapi-starter-webmvc-ui 2.5.0与Spring Boot 3.2的依赖兼容性,可通过Maven依赖树排查冲突:mvn dependency:tree

3. 修正OpenAPI Generator插件配置

确保插件生成代码时保留示例相关注解,在插件配置中添加以下参数:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>7.6.0</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
        <generatorName>spring</generatorName>
        <configOptions>
          <useSpringBoot3>true</useSpringBoot3>
          <enableAnnotations>true</enableAnnotations>
          <generateApiDocumentation>true</generateApiDocumentation>
          <examplePropertySuffix>Example</examplePropertySuffix>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

若生成的API接口类缺失示例注解,可手动补充:

@GetMapping("/tests")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200", description = "成功响应",
        content = @Content(mediaType = "application/json",
            examples = @ExampleObject(name = "SampleResponse", value = "{\"id\":1,\"name\":\"测试数据\"}")))
})
public ResponseEntity<TestResponse> getTests() {
    // 业务逻辑实现
}

4. 清理缓存并重启应用

  • 执行mvn clean install -U清理Maven缓存并重新构建
  • 重启Spring Boot应用,确保新配置和生成代码生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:14:53