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

如何阻止openapi-generator Maven插件生成Builder风格方法?

问题:OpenAPI Generator生成Builder风格链式方法引发Jackson识别异常

问题背景

环境:OpenJDK 17.0.9 + Maven 3.8.6
基于以下OpenAPI Schema(路径src/main/resources/schema.yaml)生成模型:

openapi: 3.0.3
info:
  title: Test
  version: 0.0.0
paths:
  /none:
    get:
      responses:
        "200":
          description: API not generated yet
components:
  schemas:
    operation:
      type: object
      properties:
        settings:
          $ref: "./settings.yaml#/Settings"

生成的Java类(路径target/generated-sources/openapi/src/main/java/com/test/model/)里,除了预期的构造器、getter/setter,还多出了Builder风格的链式方法:

public OperationDTO settings(SettingsDTO settings) {
    this.settings = settings;
    return this;
}

这个方法被Jackson误识别为setter,导致Swagger UI的schema中出现不存在的"tings"字段,校验时也会报错。需要仅通过插件配置阻止生成这类方法,不手动修改类。

链式方法生成原因

OpenAPI Generator的spring生成器默认开启了fluent builder特性,生成这种链式方法是为了支持对象的链式构建(比如new OperationDTO().settings(xxx).xxx())。但Jackson的setter识别规则会把这类以属性名直接命名的方法误解析:它会去掉方法名开头的小写前缀,把settings解析为对应字段tings,从而引发异常。

解决办法

修改Maven插件的configOptions,添加fluentBuilder=false配置项,禁用fluent builder生成:

<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>7.2.0</version>
    <executions>
        <execution>
            <id>generate-model</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <!-- 原有配置保留 -->
                <inputSpec>${project.basedir}/src/main/resources/schemas/schema.yaml</inputSpec>
                <generatorName>spring</generatorName>
                <modelPackage>com.test.model</modelPackage>
                <modelNameSuffix>DTO</modelNameSuffix>
                <generateSupportingFiles>false</generateSupportingFiles>
                <generateApis>false</generateApis>
                <generateModelDocumentation>true</generateModelDocumentation>
                <configOptions>
                    <useSpringBoot3>true</useSpringBoot3>
                    <openApiNullable>true</openApiNullable>
                    <useSwaggerUI>true</useSwaggerUI>
                    <hideGenerationTimestamp>true</hideGenerationTimestamp>
                    <useEnumCaseInsensitive>true</useEnumCaseInsensitive>
                    <!-- 添加此行禁用链式方法生成 -->
                    <fluentBuilder>false</fluentBuilder>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

执行mvn clean compile重新生成模型后,类中只会保留标准的setSettings方法,Jackson能正确识别字段,Swagger UI的异常也会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 18:38:10