OpenAPI Generator Maven 插件配置详解(SpringBoot集成)

0-1开始Java语言编程之路
一、Ubuntu下Java语言环境搭建 | MacOS下使用Jenv管理多JDK版本
二、Ubuntu下Docker环境安装 | MacOS下Docker安装与配置
三、使用Docker搭建本地Nexus Maven私有仓库
四、Ubuntu下使用VisualStudioCode进行Java开发
五、从Swagger到OpenAPI,SpringBoot集成StepByStep
六、OpenAPI Generator Maven 插件配置详解(SpringBoot集成)


上一篇文章介绍了OpenAPI Generator Maven插件的基本使用,大体来讲分三步:

  • 定义API Spec,也就是xxx-service-api-spec.yaml
  • 通过OpenAPI Generator Maven插件来生成SpringbootApplication框架代码
  • 在框架代码基础上实现具体的业务逻辑

但还是有一些需要注意的点,比如Maven插件的配置,今天就带大家一起来看一下Maven插件都有哪些参数,又如何配置,以及又有哪些常用的配置项。

参数说明

参数名说明示例
verbose是否启用详细模式,默认值为 falsetrue
inputSpec指定 OpenAPI 规范文件的路径src/main/resources/openapi.yaml
inputSpecRootDirectory指定本地包含规范文件的根目录src/main/resources
mergedFileName指定合并后规范文件的名称merged-api.yaml
language目标生成语言(已废弃,使用 generatorName 代替)java
generatorName目标代码生成器名称spring
cleanupOutput是否在生成前清理输出目录,默认值为 falsetrue
output目标输出路径,默认 ${project.build.directory}/generated-sources/openapigenerated-code
gitHostGit 仓库主机,例如 gitlab.comgithub.com
gitUserIdGit 用户 IDmy-user
gitRepoIdGit 仓库 IDmy-repo
collapsedSpec指定 OpenAPI 规范的单文件表示路径openapi-collapsed.yaml
includeCollapsedSpecInArtifacts是否在 Maven 构件中包含合并规范文件,默认 falsetrue
templateDirectoryMustache 模板所在目录src/main/resources/templates
templateResourcePathMustache 模板资源路径,优先于 templateDirectoryclasspath:/templates
engine使用的模板引擎,默认 mustache,可选 handlebarsmustache
auth远程获取 OpenAPI 定义时添加的授权头“Authorization: Bearer xyz”
configurationFile指定 JSON 格式的配置文件路径config.json
skipOverwrite是否跳过已存在文件的覆盖,默认 falsetrue
apiPackage生成的 API 类所在的包com.example.api
modelPackage生成的模型类所在的包com.example.model
invokerPackage生成的调用类所在的包com.example.invoker
packageName生成对象的默认包名com.example
groupId在 pom.xml 或 build.gradle 中设置项目的 Group IDcom.example
artifactId在 pom.xml 或 build.gradle 中设置项目的 Artifact IDopenapi-client
artifactVersion在 pom.xml 或 build.gradle 中设置项目的版本1.0.0
library选择库模板(子模板)jersey2
modelNamePrefix为模型类和枚举类设置前缀My
modelNameSuffix为模型类和枚举类设置后缀Dto
apiNameSuffix为 API 类设置后缀Controller
ignoreFileOverride指定 .openapi-generator-ignore 文件路径.openapi-generator-ignore
httpUserAgent自定义 User-Agent 头信息MyGenerator/1.0
removeOperationIdPrefix移除 operationId 前缀true
skipOperationExample跳过 API 示例生成true
logToStderr记录日志到标准错误输出true
enablePostProcessFile启用文件后处理钩子true
skipValidateSpec是否跳过规范文件的验证,默认 falsetrue
strictSpec是否严格遵循 OpenAPI 规范true
openapiNormalizer设定 OpenAPI 规范归一化规则RULE_1=true,RULE_2=original
generateAliasAsModel是否将别名(数组、映射)作为模型生成true
supportingFilesToGenerate指定要生成的支持文件列表,以逗号分隔,默认生成所有支持文件APIUtil.java
configOptions生成器特定的参数映射{“dateLibrary”:“java8”}
instantiationTypes设定实例化类型映射array=ArrayList,map=HashMap
importMappings设定类与其 import 之间的映射MyType=com.example.MyType
typeMappings设定 OpenAPI 类型与生成代码类型之间的映射string=String
schemaMappings设定架构名称的映射schema_a=Cat
nameMappings设定属性名称的映射property_a=firstProperty
modelNameMappings设定模型名称的映射model_a=FirstModel
parameterNameMappings设定参数名称的映射param_a=first_parameter
generateApis是否生成 API 代码,默认 truetrue
generateModels是否生成模型代码,默认 truetrue
generateSupportingFiles是否生成支持文件,默认 truetrue
generateModelTests是否生成模型测试代码true
generateModelDocumentation是否生成模型文档true
generateApiTests是否生成 API 测试代码true
generateApiDocumentation是否生成 API 文档true
skip是否跳过代码生成false
dryRun是否启用 dry-run 模式,不生成文件,仅显示摘要true
globalProperties设定全局属性,影响所有代码生成阶段{“apiDocs”:“false”}
serverVariableOverrides指定服务器变量的重写{“basePath”:“/v2”}
reservedWordsMappings保留关键字的映射id=identifier
generateModelTests是否生成模型测试代码true
generateModelDocumentation是否生成模型文档true
generateApiTests是否生成 API 测试代码true
generateApiDocumentation是否生成 API 文档true
addCompileSourceRoot是否将输出目录添加到编译源true
addTestCompileSourceRoot是否将输出目录添加到测试编译源false
environmentVariables已废弃,请使用 globalPropertiesN/A

上面标红的参数为常用的参数,其中 supportingFilesToGenerate , configOptions 是复合类型的参数,具体要怎么配置我们需要去查看Generator的源码才能知道一二。

supportingFilesToGenerate 参数说明

下载源代码

首先大家需要从OpenAPI Generator Github Repository下载源代码。

arsenal@txzq1899:~/Workspace$ git clone git@github.com:OpenAPITools/openapi-generator.git

在IDE中打开项目(推荐使用VSCode)

要了解supportingFilesToGenerate要如何配置,我们需要从源码中寻找答案,以Spring为例,如果我们是生成Spring的代码,我们需要查看SpringCodegen.java这个文件。

打开SpringCodegen.java

supportFiles
通过Ctrl + F 查找:supportingFiles.add , 我们可以看到总共有18处。

PS:我们可以看到 org.openapitools.codegen.languages 这个package下边有很多的Codegen,不同的Codegen其supportingFiles是不一样的,大家可自行研究。

SpringCodeGen supportingFiles 整理

根据 SpringCodegen 的 processOpts() 方法及相关逻辑,可以整理出 supportingFiles 里有哪些文件,以及它们在什么情况下会被添加。以下是分析结果:

FileNameCondition(条件)
pom-sb3.mustache → pom.xmluseSpringBoot3 == true
pom.mustache → pom.xmluseSpringBoot3 == false
README.mustache → README.md总是添加
swagger-ui.mustache → swagger-ui.htmluseSwaggerUI == true 且 selectedDocumentationProviderRequiresSwaggerUiBootstrap() == true
openapi2SpringBoot.mustache → OpenApiGeneratorApplication.javainterfaceOnly == false 且 library == SPRING_BOOT
SpringBootTest.mustache → OpenApiGeneratorApplicationTests.javainterfaceOnly == false 且 library == SPRING_BOOT
RFC3339DateFormat.mustache → RFC3339DateFormat.javainterfaceOnly == false 且 library == SPRING_BOOT
apiKeyRequestInterceptor.mustache → ApiKeyRequestInterceptor.javalibrary == SPRING_CLOUD_LIBRARY
clientPropertiesConfiguration.mustache → ClientPropertiesConfiguration.javalibrary == SPRING_CLOUD_LIBRARY 且 OpenAPI 配置了 OAuth 方法
clientConfiguration.mustache → ClientConfiguration.javalibrary == SPRING_CLOUD_LIBRARY
application.mustache → application.propertiesinterfaceOnly == false 且 library == SPRING_BOOT
homeController.mustache → HomeController.javainterfaceOnly == false 且 library == SPRING_BOOT
openapi.mustache → openapi.yamlinterfaceOnly == false 且 library == SPRING_BOOT
springdocDocumentationConfig.mustache → SpringDocConfiguration.javainterfaceOnly == false 且 library == SPRING_BOOT 且 reactive == false 且 apiFirst == false 且 getDocumentationProvider() == SPRINGDOC
openapiDocumentationConfig.mustache → SpringFoxConfiguration.javainterfaceOnly == false 且 library == SPRING_BOOT 且 reactive == false 且 apiFirst == false 且 getDocumentationProvider() == SPRINGFOX
httpInterfacesConfiguration.mustache → HttpInterfacesAbstractConfigurator.javalibrary == SPRING_HTTP_INTERFACE
apiUtil.mustache → ApiUtil.javalibrary == SPRING_BOOT
converter.mustache → EnumConverterConfiguration.javainterfaceOnly == false 且 library == SPRING_BOOT 且 openAPI 里包含 enum
apiDelegate.mustache → Delegate.javadelegatePattern == true 且 delegateMethod == false

通常来讲,我们第一次运行Codegen时,不需要配置supportingFilesToGenerate,Codegen会根据上面的条件来默认生成一些文件,比如:

  • README.MD
  • pom.xml(后续不能覆盖)
  • SpringDocConfiguration.java
  • OpenApiGeneratorApplication.java
  • HomeController.java
  • openapi.yaml(通常我们会删除该文件,后续也不再生成)
    等,在项目初始化完后再根据项目实际情况对基础框架代码进行相应的调整,比如 pom.xml 文件,第一次生成后,我们会引用一些其它的项目依赖,我们肯定会对pom.xml进行修改,那后面这个文件就不能被覆盖,我们就需要配置supportingFilesToGenerate,在这里显示指定要生成的文件。比如:APIUtil.java,或者 空,这样就会避免覆盖 pom.xml, SpringbootApplication入口文件等。

上面这些文件的生成,会参考 modules/openapi-generator/src/main/resources/JavaSpring 目录下的模板文件,比如 apiUtil.mustache

ConfigOptions 参数解析

大家可以从以下的源码中看到ConfigOptions都有哪些参数
modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java

ConfigOptions 参数分析

configOptions 包含了一系列 键值对 (Key-Value Pairs),每个键代表一个 OpenAPI 代码生成器的配置项,而值则是相应的设定。以下是主要的 configOptions 及其功能:

参数名称功能
instantiation-types定义对象的实例化类型映射,例如将 array 映射为 ArrayList
import-mappings定义模型类的 Java 包路径映射,例如 LocalDateTime -> java.time.LocalDateTime
schema-mappings定义 OpenAPI schema 类型到 Java 类型的映射
inline-schema-name-mappings自定义内联 Schema 的命名映射
inline-schema-options配置是否允许内联 Schema
openapi-normalizer配置 OpenAPI 规范的标准化规则
type-mappingsOpenAPI 数据类型到 Java 类型的映射,例如 integer -> Integer
language-specific-primitives指定代码生成器支持的原生数据类型,例如 BigDecimal, LocalDateTime
openapi-generator-ignore-list配置忽略的 OpenAPI 代码生成文件
additional-properties自定义代码生成的额外属性,决定生成代码的特性
server-variables配置服务器 URL 变量
reserved-words-mappings配置保留关键字的替代映射,例如 class -> clazz
name-mappings自定义生成的 API、模型或参数的名称
parameter-name-mappings配置参数名称的映射规则
model-name-mappings配置模型名称的映射规则
enum-name-mappings配置枚举名称的映射规则
operation-id-name-mappings配置 OpenAPI 操作 ID 的映射规则
source-folder代码生成的源代码目录

有关使用SpringBoot集成Openapi-generator-maven插件的详细配置说明到这里就完成了。大家可以收藏本文章,并仔细研究每一个配置,根据项目的实际情况进行配置。

关注我的公众号

欢迎大家关注、点赞、转发,一起交流软件开发、架构设计、云原生技术。
TXZQ聊IT技术与架构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值