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

Springdoc混合自动生成OpenAPI Spec与本地JSON Schema的方法

解决方案

1. 读取本地Schema文件并解析为OpenAPI Schema对象

不要硬编码JSON字符串,通过Spring的ResourceLoader读取classpath下的foo.json,再用Jackson将其解析为OpenAPI标准的Schema结构:

2. 排除Foo类的自动Schema生成

为避免Springdoc自动生成的Foo类Schema与手动编写的冲突,给Foo类添加@Hidden注解:

@Hidden
public class Foo {
    // 原有复杂结构
}

3. 实现OpenApiCustomizer完成Schema融合

在配置类中读取并解析foo.json,将手动编写的Schema合并到自动生成的OpenAPI组件中:

@Configuration
public class SpringDocConfig {

    private final ObjectMapper objectMapper;
    private final ResourceLoader resourceLoader;

    public SpringDocConfig(ObjectMapper objectMapper, ResourceLoader resourceLoader) {
        this.objectMapper = objectMapper;
        this.resourceLoader = resourceLoader;
    }

    @Bean
    public OpenApiCustomizer openApiCustomiser() throws IOException {
        // 读取classpath下的foo.json文件
        Resource resource = resourceLoader.getResource("classpath:foo.json");
        String fooJsonContent = Files.readString(Paths.get(resource.getURI()));

        // 将JSON解析为OpenAPI的Schema映射结构
        Map<String, Schema> manualSchemas = objectMapper.readValue(
                fooJsonContent,
                new TypeReference<Map<String, Schema>>() {}
        );

        return openApi -> {
            // 获取自动生成的schemas集合,合并手动编写的Schema
            Map<String, Schema> autoGeneratedSchemas = openApi.getComponents().getSchemas();
            autoGeneratedSchemas.putAll(manualSchemas);
        };
    }
}

4. 确保响应对象字段引用正确

如果foo.json中定义的Schema名称为Foo,给MyMixedResponse的字段添加@Schema注解指定引用:

@Data
public class MyMixedResponse {
    private int id;
    private String attr1;
    @Schema(ref = "#/components/schemas/Foo")
    private Foo complexFoo;
}

关键说明

  • Springdoc集成了OpenAPI的Jackson模块,使用Spring自带的ObjectMapper即可正确将JSON转换为Schema对象。
  • 若foo.json包含关联的子Schema(如Foo的子类、枚举),只要符合OpenAPI规范,会被一并解析并合并。
  • putAll方法会覆盖重名Schema,确保手动编写的内容优先级更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 09:53:12