openapi-generator-maven-plugin自动生成HTTP远程调用客户端

发布于:2025-06-23 ⋅ 阅读:(22) ⋅ 点赞:(0)

Java开发中调用http接口的时候,有很多可选的技术方案,比如:HttpURLConnection、RestTemplate、WebClient、Feign、Retrofit、Okhttp等,今天我们来看一个更优的技术方案OpenAPI Generator(http://openapi-generator.tech/)

OpenAPI Generator

OpenAPI Generator 是一个开源工具集,用于根据 OpenAPI/Swagger 规范文件自动生成客户端 SDK、服务器端存根 (stub) 和 API 文档。支持 50+ 种语言和框架(Java、Python、Go、TypeScript、C#等),支持 OpenAPI 2.0 (Swagger) 和 3.x 规范,可处理 JSON 或 YAML 格式的 API 描述文件。

下面我们来看一下使用openapi-generator-maven-plugin生成利用resttemplate做远程调用的demo。

服务提供者UserService

1)api接口

 @GetMapping("/{id}")
    public UserDto getById(@PathVariable int id){
        return db.get(id);
    }

2)生成openapi-doc的json文件
添加依赖

<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
	<version>2.5.0</version>
</dependency>

访问:http://localhost:8081/v3/api-docs,得到

{
	"openapi": "3.0.1",
	"info": {
		"title": "OpenAPI definition",
		"version": "v0"
	},
	"servers": [{
		"url": "http://localhost:8081",
		"description": "Generated server url"
	}],
	"paths": {
		"/{id}": {
			"get": {
				"tags": ["user-controller"],
				"operationId": "getById",
				"parameters": [{
					"name": "id",
					"in": "path",
					"required": true,
					"schema": {
						"type": "integer",
						"format": "int32"
					}
				}],
				"responses": {
					"200": {
						"description": "OK",
						"content": {
							"*/*": {
								"schema": {
									"$ref": "#/components/schemas/UserDto"
								}
							}
						}
					}
				}
			}
		}
	},
	"components": {
		"schemas": {
			"UserDto": {
				"type": "object",
				"properties": {
					"id": {
						"type": "integer",
						"format": "int32"
					},
					"name": {
						"type": "string"
					}
				}
			}
		}
	}
}

服务消费者OrderService

1)引入前面生成的json文件,存放在order服务的src/resources/api/user-api.json。

2)添加openapi-generator-maven-plugin

<!--https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator-maven-plugin-->
<plugin>
	<groupId>org.openapitools</groupId>
	<artifactId>openapi-generator-maven-plugin</artifactId>
	<version>7.12.0</version>
	<executions>
		<execution>
			<id>rest template</id>
			<goals>
				<goal>generate</goal>
			</goals>
			<configuration>
				<inputSpec>${project.basedir}/src/main/resources/api/user-api.json</inputSpec>
				<generatorName>java</generatorName>
				<configOptions>
					<sourceFolder>src/main/java</sourceFolder>
					<java8>true</java8>
					<dateLibrary>java8</dateLibrary>
					<useJakartaEe>true</useJakartaEe>
				</configOptions>
				<output>${project.basedir}/target/generated-sources/openapi</output>
				<!--<packageName>com.github.xjs.user</packageName>-->
				<apiPackage>com.github.xjs.user</apiPackage>
				<modelPackage>com.github.xjs.user.model</modelPackage>
				<invokerPackage>com.github.xjs.user.invoker</invokerPackage>
				<library>resttemplate</library>
				<generateModelTests>false</generateModelTests>
				<generateApiTests>false</generateApiTests>
				<generateApiDocumentation>false</generateApiDocumentation>
			</configuration>
		</execution>
<!--                    add other clients-->
<!--					<execution> -->
<!--					</execution>-->
	</executions>
</plugin>

解释下几个重点的配置项:

  • inputSpec:指定 OpenAPI 规范文件路径:src/main/resources/api/user-api.json,支持 JSON/YAML 格式,可以是本地文件或 URL。
  • generatorName:生成目标为 Java 客户端代码(其他选项如 spring、kotlin 等)。
  • library:resttemplate,使用 Spring 的 RestTemplate 作为 HTTP 客户端库(替代方案:webclient、feign 等)。
  • output: 生成代码的输出目录:target/generated-sources/openapi, 默认会被 Maven 自动添加到编译路径。
  • packageName: com.github.xjs.user, 所有生成代码的根包名(API 类、模型类等会放在此包下)。
  • sourceFolder: src/main/java, 生成的 Java 代码直接输出到 src/main/java(覆盖默认的生成路径结构)。
  • java8:true, 启用 Java 8 特性(如 Optional、函数式接口等)。
  • dateLibrary: java8, 使用 java.time 包(Java 8 的日期时间库,替代 java.util.Date)。
  • useJakartaEe: true, 使用 Jakarta EE 注解(如 @jakarta.annotation.Generated),而非旧的 javax.annotation
  • generateModelTests:false,不生成模型类的测试代码(如 UserTest.java)。
  • generateApiTests:false,不生成 API 接口的测试代码(如 UserApiTest.java)。
  • generateApiDocumentation:false, 不生成 API 文档(如 README.md 或 docs/ 目录)。

3)生成源代码
命令行执行mvn clean compile就会生成对应的http调用代码:

target/generated-sources/openapi/
  └── src/main/java/
      └── com/
          └── github/
              └── xjs/
                  └── user/
                      ├── api/       # API 接口(如 UserApi.java)
                      ├── model/     # 数据模型(如 User.java)
                      └── ApiClient.java  # 核心客户端配置

4)服务调用

// 创建ApiClient 
ApiClient apiClient = new ApiClient();
// 设置生产者服务的baseurl
apiClient.setBasePath("http://localhost:8081");
// 创建ControllerApi
UserControllerApi userControllerApi = new UserControllerApi(apiClient);
// 利用ControllerApi远程调用api接口
UserDto user = userControllerApi.getById(userId);

完整的源码下载:https://github.com/xjs1919/learning-demo/tree/master/openapi-generator-demo


网站公告

今日签到

点亮在社区的每一天
去签到