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

SpringFox Swagger不展示OpenAPI YAML全局示例问题咨询

SpringFox Swagger与OpenAPI生成器忽略全局响应示例的问题解决

1. 为什么Spring代码生成器会忽略该全局示例?

  • OpenAPI Generator 6.0.1的Spring服务端模板默认仅处理Schema内部的字段级示例,对响应顶层(Schema外)的全局example/examples字段没有内置映射逻辑,不会自动将其转换为代码中的注解或示例代码。
  • Swagger编辑器生成Spring代码时依赖同一系列模板,因此同样会忽略这类全局示例。
  • 该版本的OpenAPI Generator对OpenAPI 3.0的响应示例支持不完善,未覆盖顶层示例的解析场景。

2. 如何配置才能让SpringFox Swagger显示该全局示例?

方案一:调整OpenAPI YAML格式适配SpringFox

SpringFox 3.0.0对OpenAPI 3.0的examples数组支持有限,优先使用单个example字段定义全局示例,确保格式兼容:

/v1/getSome:
  get:
    responses:
      '200':
        description: 成功返回数据
        schema:
          $ref: '#/components/schemas/SomeResponse'
        # 全局示例,覆盖字段级示例
        example:
          id: 1001
          content: "全局示例内容"
          status: "SUCCESS"

方案二:自定义SpringFox配置手动绑定示例

通过Swagger配置类的Docket实例手动构建包含全局示例的响应:

@Configuration
public class Swagger3Config {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.OAS_30)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.your.project.api"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo())
                .globalResponses(HttpMethod.GET, buildGlobalResponses());
    }

    private List<Response> buildGlobalResponses() {
        // 针对/v1/getSome接口的200响应添加全局示例
        Response successResp = new ResponseBuilder()
                .description("成功响应")
                .representation(MediaType.APPLICATION_JSON)
                .model(model -> model.example("{\"id\":1001,\"content\":\"全局示例内容\",\"status\":\"SUCCESS\"}"))
                .build();
        return Collections.singletonList(successResp);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("业务API文档")
                .version("v1")
                .build();
    }
}

方案三:配置OpenAPI Generator生成示例代码

在生成器配置中添加参数开启响应示例支持,以Maven插件为例:

<plugin>
    <groupId>org.openapi.generator</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>6.0.1</version>
    <executions>
        <execution>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec>
                <generatorName>spring</generatorName>
                <additionalProperties>
                    <!-- 开启响应示例生成 -->
                    <useResponseExample>true</useResponseExample>
                    <interfaceOnly>true</interfaceOnly>
                </additionalProperties>
            </configuration>
        </execution>
    </executions>
</plugin>

开启useResponseExample=true后,生成器会将全局示例添加到@ApiResponse注解的example属性中。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:57:35