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

springdoc-openapi-maven-plugin生成YAML出现example: null如何解决?

问题:springdoc-openapi生成的YAML契约出现example: null,如何避免?

将jackson-databind依赖升级到2.14.0后,使用springdoc-openapi-maven-plugin生成YAML格式的API契约时,发现所有路径/请求参数的schema都会自动生成example: null字段,示例如下:

openapi: 3.0.1
paths:
  /myapi/v1/resource/{id}:
    get:
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            example: null
        - name: param1
          in: query
          required: true
          schema:
            type: string
            example: null

插件配置(pom.xml):

<plugin>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-maven-plugin</artifactId>
  <version>1.4</version>
  <configuration>
    <apiDocsUrl>http://localhost:8080/v3/api-docs.yaml</apiDocsUrl>
    <outputFileName>myYamlFile.yaml</outputFileName>
    <outputDir>/home/</outputDir>
  </configuration>
  <executions>
    <execution>
      <id>integration-test</id>
      <goals>
        <goal>generate</goal>
      </goals>
    </execution>
  </executions>
</plugin>

对应的ResourceController基础代码:

@RestController
@RequestMapping("/myapi/v1/resource")
public class ResourceController {
  @GetMapping("/{id}")
  public ResourceDTO getResourceInfo(@PathVariable("id") String resourceId, @RequestParam(value="param1") String param1) {
    [...]
  }
}

解决方案

1. 升级springdoc-openapi版本适配Jackson 2.14+

旧版本的springdoc-openapi(如1.4)对Jackson 2.14的空值序列化逻辑兼容不佳,导致自动生成example: null。建议将springdoc相关依赖及插件升级到1.6.x及以上版本(例如1.6.14):

修改pom.xml中的插件版本:

<plugin>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-maven-plugin</artifactId>
  <version>1.6.14</version>
  <!-- 其余配置保持不变 -->
</plugin>

同时确保项目中的springdoc-openapi-core依赖也同步升级到对应版本:

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-core</artifactId>
  <version>1.6.14</version>
</dependency>

2. 禁用自动生成默认参数示例

如果不想升级版本,可以通过springdoc的配置关闭自动生成参数的默认示例,在application.properties或application.yml中添加:

application.properties:

springdoc.api-docs.default-example-parameter-enabled=false

application.yml:

springdoc:
  api-docs:
    default-example-parameter-enabled: false

这个配置会阻止springdoc为未显式设置示例的参数生成默认示例,自然不会出现example: null。

3. 自定义Jackson序列化规则(兜底方案)

如果上述方法都无法生效,可以配置Jackson序列化时忽略null值字段,确保example: null不会被写入YAML:

创建自定义的Jackson配置类:

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 序列化时忽略null值字段
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }
}

不过这个方法会全局生效,影响所有Jackson序列化的场景,需要根据项目情况谨慎使用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:45:34