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

Spring Boot中OpenAPI代码生成器复用已有枚举避免重复生成

解决OpenAPI代码生成器重复生成枚举的问题

要复用已生成的Weekday枚举,需要从格式统一和插件配置两方面入手,具体步骤如下:

1. 统一API文件格式

你的主文件是OpenAPI 3.0.3格式,但commons.yml是Swagger 2.0格式,格式不一致会导致生成器无法识别已有枚举。先将commons.yml转换为OpenAPI 3.x格式:

openapi: 3.0.3
info:
  title: Commons file
  description: Common elements used across all of the REST APIs
  version: 1.0.0
paths: {}
components:
  schemas:
    weekday:
      type: string
      enum:
        - MON
        - TUE
        - WED
        - THU
        - FRI
        - SAT
        - SUN
      description: Day of a week.
      example: FRI

2. 配置Maven插件复用枚举

在openapi-generator-maven-plugin中添加importMappings参数,指定weekday枚举对应的已生成类的全限定名,让生成器直接引用该类而非重复生成。

完整插件配置示例:

<plugin>
  <groupId>org.openapitools</groupId>
  <artifactId>openapi-generator-maven-plugin</artifactId>
  <version>7.6.0</version> <!-- 使用最新稳定版 -->
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <inputSpec>${project.basedir}/src/main/resources/openapi/main.yml</inputSpec>
        <generatorName>spring</generatorName>
        <apiPackage>com.yourcompany.api</apiPackage>
        <modelPackage>com.yourcompany.model</modelPackage>
        
        <!-- 核心配置:映射枚举到已存在的类 -->
        <importMappings>
          <importMapping>weekday=com.yourcompany.commons.enums.Weekday</importMapping>
        </importMappings>

        <configOptions>
          <useSpringBoot3>true</useSpringBoot3>
          <interfaceOnly>true</interfaceOnly> <!-- 按需启用,仅生成API接口 -->
          <java8>true</java8>
        </configOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

3. 额外注意事项

  • 确保com.yourcompany.commons.enums.Weekday类已提前生成(可单独通过commons.yml生成该枚举)。
  • 如果需要同时处理多个API文件,可在inputSpec中用逗号分隔路径,比如:
    <inputSpec>${project.basedir}/src/main/resources/openapi/main.yml,${project.basedir}/src/main/resources/openapi/commons.yml</inputSpec>
    
  • 若不想生成任何新枚举,可添加<skipEnumGeneration>true</skipEnumGeneration>到configOptions,但需确保所有枚举都已通过importMappings映射。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:51:00