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

SpringCodegen生成JsonTypeInfo.As.EXISTING_PROPERTY致反序列化字段丢失求配置

解决SpringCodegen生成@JsonTypeInfo时include属性为PROPERTY的方案

一、通过OpenAPI定义调整

如果你的OpenAPI yml文件中使用了**多态类型(oneOf/anyOf)**并配置了discriminator,可以在对应schema中添加扩展字段指定Jackson类型信息的包含方式:

  • 在包含discriminator的基类schema里,添加x-jackson-type-info-include: PROPERTY扩展,示例如下:
components:
  schemas:
    BaseEntity:
      type: object
      discriminator:
        propertyName: type
      x-jackson-type-info-include: PROPERTY
      properties:
        type:
          type: string
    EntityA:
      allOf:
        - $ref: '#/components/schemas/BaseEntity'
        - type: object
          properties:
            fieldA:
              type: string
    EntityB:
      allOf:
        - $ref: '#/components/schemas/BaseEntity'
        - type: object
          properties:
            fieldB:
              type: integer

该扩展会直接告知SpringCodegen生成@JsonTypeInfo(include = JsonTypeInfo.As.PROPERTY)注解。

二、通过Maven OpenAPI插件配置调整

在Maven pom.xml的OpenAPI Generator插件配置中,添加全局参数typeInfoInclude并设置为PROPERTY,统一控制所有多态类的注解生成:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>你的插件版本</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/openapi.yml</inputSpec>
        <generatorName>spring</generatorName>
        <configOptions>
          <!-- 其他已有配置 -->
          <typeInfoInclude>PROPERTY</typeInfoInclude>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

此配置无需修改OpenAPI定义,直接覆盖插件默认的注解生成逻辑。

注意事项

  • 确保使用的OpenAPI Generator(SpringCodegen)版本在v5.0及以上,该版本开始完善了Jackson注解生成的参数控制。
  • 重新生成代码前执行mvn clean清理缓存,避免旧生成文件干扰结果。

内容的提问来源于stack exchange,提问作者Victor Trapiello Fernández

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:35:20