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

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接口

java 复制代码
 @GetMapping("/{id}")
    public UserDto getById(@PathVariable int id){
        return db.get(id);
    }

2)生成openapi-doc的json文件

添加依赖

xml 复制代码
<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
	<version>2.5.0</version>
</dependency>

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

JSON 复制代码
{
	"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

XML 复制代码
<!--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>
				<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调用代码:

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

4)服务调用

java 复制代码
// 创建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

相关推荐
学长毕设31 分钟前
基于SpringBoot 车辆租赁系统平台-附源码
java·spring boot·后端
Flynt2 小时前
Spring AI Alibaba 真停更了?我把它的 GitHub 翻了个底朝天
java·spring·开源
她的男孩6 小时前
Spring Boot 接 Flowable:请假单要同时走财务和行政,包容分支和默认分支怎么配
java·spring boot·工作流引擎
咖啡八杯7 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依
北冥有鱼8 小时前
从 bean::method 里抠出注解:Java 方法引用元数据反查全记录
java·后端
CoderYanger8 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第四弹):@ControllerAdvice 源码分析+案例代码
java·数据库·spring boot·后端·spring·java-ee·mybatis
玖米GEO运营王总监11 小时前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
AI人工智能+电脑小能手13 小时前
集合按大小切片分批,这个Java工具类5个方法含基本类型数组
java·工具类·批量处理·集合分片·分批调用
SimonKing13 小时前
高星红果短剧的TV版|桌面版都在这里了
java·后端·程序员
Rain的Java大神之路13 小时前
大四 Java 校招速成路线:从高频八股到可部署项目,30 天、8 周、12 周都能照着练
java·后端·面试