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

如何通过openapi-generator-maven-plugin实现多日期类代码生成?

问题解答:openapi-generator-maven-plugin 6.0.1 实现多日期类型映射

用户问题

我正在使用版本为6.0.1的openapi-generator-maven-plugin,当前配置将OffsetDateTime映射为ZonedDateTime。现在需要为不同的DTO模型分别使用ZonedDateTime、LocalDateTime和Date等Java日期类,示例OpenAPI定义如下:

SomeDto:
  required:
    - dateTime
  type: object
  properties:
    dateTime:
      type: string
      format: ZonedDateTime

SomeOtherDto:
  required:
    - dateTime
  type: object
  properties:
    dateTime:
      type: string
      format: LocalDateTime

请问能否通过该插件实现这样的逻辑?

可以实现,具体配置步骤如下:

1. 添加类型映射配置

在maven插件的配置中,通过typeMappings定义OpenAPI自定义格式到Java类的映射,再通过importMappings指定对应的包路径:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>6.0.1</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <!-- 此处保留你的其他基础配置,如spec文件路径、生成目录等 -->
        <typeMappings>
          <typeMapping>ZonedDateTime=ZonedDateTime</typeMapping>
          <typeMapping>LocalDateTime=LocalDateTime</typeMapping>
          <typeMapping>Date=Date</typeMapping>
        </typeMappings>
        <importMappings>
          <importMapping>ZonedDateTime=java.time.ZonedDateTime</importMapping>
          <importMapping>LocalDateTime=java.time.LocalDateTime</importMapping>
          <importMapping>Date=java.util.Date</importMapping>
        </importMappings>
      </configuration>
    </execution>
  </executions>
</plugin>

2. 配置日期库适配

如果使用java-spring生成器,指定dateLibrary=java8,让插件自动适配Java 8+日期类的序列化/反序列化:

<configuration>
  <!-- 其他配置 -->
  <generatorName>java-spring</generatorName>
  <dateLibrary>java8</dateLibrary>
</configuration>

若使用其他生成器(如java-jaxrs),需确保项目依赖的序列化组件(如Jackson)支持这些日期类型,可额外添加jackson-datatype-jsr310依赖处理java.time类。

3. 验证OpenAPI定义

确保你的OpenAPI规范中,日期字段的format值与typeMappings中定义的完全一致,插件会自动按映射生成对应的Java字段类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:10:32