基于已有类的OpenAPI代码生成:共享模型复用需求问询
解决OpenAPI生成器重复生成共享模型并跨服务引用公共类的方案
问题场景
我们采用多微服务架构,存在共享模型(比如Address):
- 公共模块的
common.yaml定义了Address模型 - 客户域服务
customer-service.yaml、公司域服务company-service.yaml的模型中通过$ref引用Address - 编排型服务
application-service.xml的模型也引用了相关域对象
使用OpenAPI生成器后,会在各个服务模块中生成重复的Address类(如com.xxx.customer.model.Address、com.xxx.company.model.Address等),现在需要让所有服务生成的代码都引用公共的com.xxx.common.model.Address,避免重复类,同时通过application API正确暴露域对象。
具体解决步骤
1. 修正OpenAPI规范中的引用路径
首先确保各个服务的OpenAPI文件里的$ref正确指向公共的Address定义:
- 本地文件引用示例(
customer-service.yaml中修改):address: $ref: './common.yaml#/components/schemas/Address' - 如果公共规范是依赖包中的资源,可使用类路径引用(部分生成器支持),或确保生成时能加载到公共规范文件。
2. 配置OpenAPI生成器,映射共享模型到公共类
针对Java生成器,通过import-mappings参数指定已存在的公共类,避免重新生成重复模型:
命令行生成方式
生成客户域服务代码时添加映射参数:
openapi-generator generate -i customer-service.yaml -g java --import-mappings Address=com.xxx.common.model.Address -o ./customer-service-gen
Maven插件配置
在服务的pom.xml中配置OpenAPI生成器插件时,添加映射规则:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <!-- 使用最新稳定版本 --> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/customer-service.yaml</inputSpec> <generatorName>spring</generatorName> <!-- 根据实际框架选择,如spring、jaxrs等 --> <configOptions> <importMappings>Address=com.xxx.common.model.Address</importMappings> <modelPackage>com.xxx.customer.model</modelPackage> <!-- 客户域模型包路径 --> <!-- 其他配置如apiPackage、interfaceOnly等按需添加 --> </configOptions> </configuration> </execution> </executions> </plugin>
Gradle插件配置
在build.gradle中添加:
openapiGenerate { generatorName = "java" inputSpec = file("src/main/resources/customer-service.yaml").path outputDir = file("$buildDir/generated-sources/openapi") configOptions = [ importMappings: "Address=com.xxx.common.model.Address", modelPackage: "com.xxx.customer.model" ] }
3. 引入公共模型依赖
将包含com.xxx.common.model.Address的公共模块打包为jar,在各个服务的构建文件中添加依赖:
- Maven:
<dependency> <groupId>com.xxx</groupId> <artifactId>common-model</artifactId> <version>1.0.0</version> <!-- 对应公共模块版本 --> </dependency> - Gradle:
implementation 'com.xxx:common-model:1.0.0'
4. 编排型服务(application-service.xml)的处理
对于XML格式的OpenAPI规范,先修正$ref路径确保指向正确的公共模型及域对象,再在生成代码时配置多模型映射:
--import-mappings Address=com.xxx.common.model.Address,Customer=com.xxx.customer.model.Customer,Company=com.xxx.company.model.Company
注意事项
- 确保所有OpenAPI规范中对共享模型的定义完全一致,避免因字段、约束差异导致生成器无法正确映射
- 如果使用远程OpenAPI规范(如HTTP地址),需确保生成器能正常访问该地址,或提前下载到本地
- 部分生成器版本对
import-mappings语法有细微差异,建议参考对应版本的官方文档调整参数
内容的提问来源于stack exchange,提问作者ticktock
相关产品推荐
相关产品推荐

