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

如何使用OpenAPI Generator Maven插件在Spring Boot中基于OpenAPI规范生成API与DTO?

OpenAPI优先的Spring Boot API开发实践

在Spring Boot项目中,如果已经有现成的OpenAPI YAML规范,正确的实践是基于规范反向生成API接口和DTO代码,而非先手写REST API和DTO再导出规范。这种「API优先」的模式能从根源上保证代码实现和接口规范的一致性,减少后期因规范变更导致的代码同步问题。

我已经搭建了一个Maven版的Spring Boot POC来验证这个流程,核心依赖OpenAPI Generator插件自动生成代码,具体步骤如下:

1. 配置Maven插件

在项目的pom.xml中加入OpenAPI Generator插件,指定规范文件路径和代码生成规则:

<build>
    <plugins>
        <plugin>
            <groupId>org.openapitools</groupId>
            <artifactId>openapi-generator-maven-plugin</artifactId>
            <version>6.6.0</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <!-- 指向你的OpenAPI YAML文件位置 -->
                        <inputSpec>${project.basedir}/src/main/resources/openapi-spec.yaml</inputSpec>
                        <!-- 生成Spring Boot适配的代码 -->
                        <generatorName>spring</generatorName>
                        <configOptions>
                            <!-- 适配你的Spring Boot版本 -->
                            <springBootVersion>3.1.0</springBootVersion>
                            <!-- 仅生成API接口,不生成默认实现类 -->
                            <interfaceOnly>true</interfaceOnly>
                            <!-- DTO类的包路径 -->
                            <modelPackage>com.example.poc.dto</modelPackage>
                            <!-- API接口的包路径 -->
                            <apiPackage>com.example.poc.api</apiPackage>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2. 准备OpenAPI规范文件

将示例YAML规范放在src/main/resources/目录下(比如命名为openapi-spec.yaml),示例片段如下:

openapi: 3.0.3
info:
  title: 用户管理API
  version: 1.0.0
paths:
  /users/{id}:
    get:
      summary: 根据ID获取用户信息
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
      responses:
        '200':
          description: 成功返回用户数据
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        username:
          type: string
        email:
          type: string

3. 执行代码生成

在项目根目录下运行Maven命令触发代码生成:

mvn clean compile

执行完成后,插件会自动在指定的包路径下生成对应的DTO类(如User.java)和REST API接口(如UsersApi.java)。

生成的API接口是一个空的抽象接口,你只需要创建实现类,在其中编写具体的业务逻辑即可——这样既完全遵循了预先定义的接口规范,又省去了手动编写DTO和接口模板代码的重复劳动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:13:11