Skip to content

配置选项详解

OpenAPI Generator 的配置选项完全指南

配置方式概览

OpenAPI Generator 提供多种配置方式:

  1. 命令行参数: 直接传递配置
  2. 配置文件: YAML/JSON 格式
  3. 环境变量: 系统级配置
  4. 编程 API: 代码中配置

全局配置选项

基础选项

选项说明示例
-i, --input-specOpenAPI 规范文件路径api/openapi.yaml
-g, --generator-name生成器名称spring, typescript-axios
-o, --output输出目录./generated
-t, --template-dir自定义模板目录./templates
-c, --config配置文件路径config.yaml

高级选项

bash
# 跳过验证
--skip-validate-spec

# 详细输出
-v, --verbose

# 生成批处理文件
--generate-batch

# 最小更新(只更新变更的文件)
--minimal-update

# 删除输出目录
--remove-operation-id-prefix

# 启用 POST 处理
--enable-post-process-file

生成器特定配置

Java Spring 配置

yaml
# spring-config.yaml
additionalProperties:
  # 包结构
  basePackage: com.company.api
  modelPackage: com.company.api.model
  apiPackage: com.company.api.controller
  configPackage: com.company.api.config
  invokerPackage: com.company.api.invoker
  
  # 项目信息
  groupId: com.company
  artifactId: api-server
  artifactVersion: 1.0.0
  artifactUrl: https://github.com/company/api-server
  artifactDescription: API Server
  
  # Java 配置
  java8: true                    # 使用 Java 8 特性
  dateLibrary: java8             # 时间库:java8, joda, legacy
  
  # Spring 配置
  library: spring-boot           # spring-boot, spring-mvc, spring-cloud
  useSpringBoot3: true          # 使用 Spring Boot 3
  reactive: false               # 使用 WebFlux
  
  # 功能开关
  useTags: true                 # 使用标签分组
  interfaceOnly: false          # 只生成接口
  delegatePattern: true         # 使用委托模式
  singleContentTypes: false     # 单一内容类型
  async: false                  # 异步方法
  responseWrapper: ""           # 响应包装类
  
  # 验证
  useBeanValidation: true       # Bean Validation
  performBeanValidation: true   # 执行验证
  
  # 文档
  documentationProvider: springdoc  # springfox, springdoc, none
  
  # 数据库
  generateSupportingFiles: true
  supportingFilesToGenerate: "ApiUtil.java,pom.xml"
  
  # 序列化
  serializableModel: false      # 实现 Serializable
  withXml: false               # XML 支持
  
  # 其他
  hideGenerationTimestamp: false
  ensureUniqueParams: true
  allowUnicodeIdentifiers: false

TypeScript 配置

yaml
# typescript-config.yaml
additionalProperties:
  # 包信息
  npmName: "@company/api-client"
  npmVersion: "1.0.0"
  npmRepository: "https://npm.company.com"
  snapshot: false
  
  # TypeScript 配置
  supportsES6: true             # ES6 支持
  withInterfaces: true          # 生成接口
  withSeparateModelsAndApi: true # 分离模型和 API
  withoutPrefixEnums: false     # 枚举不加前缀
  
  # 命名约定
  modelPropertyNaming: camelCase # camelCase, PascalCase, snake_case
  enumPropertyNaming: UPPERCASE  # UPPERCASE, camelCase, PascalCase
  paramNaming: camelCase        # 参数命名
  
  # 功能配置
  withNodeImports: true         # Node.js imports
  disallowAdditionalPropertiesIfNotPresent: true
  enumNameSuffix: Enum          # 枚举后缀
  enumPropertyNamingReplaceSpecialChar: true
  
  # 请求配置
  useSingleRequestParameter: true # 单一请求参数对象
  prefixParameterInterfaces: true # 参数接口前缀
  
  # 类型映射
  stringEnums: true            # 字符串枚举
  numericEnums: false          # 数字枚举

Python 配置

yaml
# python-config.yaml
additionalProperties:
  # 包信息
  packageName: company_api_client
  projectName: company-api-client
  packageVersion: "1.0.0"
  packageUrl: "https://github.com/company/api-client-python"
  
  # Python 配置
  library: urllib3              # urllib3, asyncio, tornado, requests
  useNose: false               # 使用 nose 测试
  recursionLimit: 2000         # 递归限制
  
  # 异步支持
  asyncio: true                # 异步 IO
  tornado: false               # Tornado 支持
  
  # 类型提示
  generateSourceCodeOnly: false # 只生成源代码
  disallowAdditionalPropertiesIfNotPresent: false

类型映射配置

基础类型映射

yaml
# 命令行使用
--type-mappings DateTime=Instant,Date=LocalDate

# 配置文件
typeMappings:
  DateTime: Instant
  Date: LocalDate
  File: Blob
  UUID: string

导入映射

yaml
# 指定类型的导入路径
importMappings:
  Instant: java.time.Instant
  LocalDate: java.time.LocalDate
  UUID: java.util.UUID
  JsonNode: com.fasterxml.jackson.databind.JsonNode

语言特定映射

yaml
# Java 类型映射
languageSpecificPrimitives:
  - String
  - boolean
  - Boolean
  - Double
  - Integer
  - Long
  - Float
  - Object
  - byte
  - ByteArray

文件生成控制

选择性生成

yaml
# 只生成特定部分
globalProperties:
  apis: true           # 生成 API
  models: true         # 生成模型
  supportingFiles: true # 生成支持文件
  apiTests: false      # 不生成 API 测试
  modelTests: false    # 不生成模型测试
  apiDocs: false       # 不生成 API 文档
  modelDocs: false     # 不生成模型文档

文件过滤

bash
# 只生成特定文件
--supporting-files-to-generate "pom.xml,README.md"

# 排除文件
--ignore-file-override .openapi-generator-ignore

自定义文件生成

yaml
files:
  # 额外文件
  - templateFile: "custom-readme.mustache"
    outputFile: "README.md"
    
  - templateFile: "docker-compose.mustache"
    outputFile: "docker-compose.yml"
    
  - templateFile: "ci-pipeline.mustache"
    outputFile: ".github/workflows/ci.yml"

命名策略配置

API 命名

yaml
# API 命名规则
apiNameSuffix: "Api"          # API 类后缀
apiNamePrefix: ""             # API 类前缀

# 示例:UserApi, OrderApi

模型命名

yaml
# 模型命名规则
modelNameSuffix: "DTO"        # 模型类后缀
modelNamePrefix: ""           # 模型类前缀

# 示例:UserDTO, OrderDTO

参数命名

yaml
# 参数命名转换
parameterNamingConvention: camelCase  # camelCase, snake_case

验证和安全配置

输入验证

yaml
# 启用验证
useBeanValidation: true
performBeanValidation: true

# 验证注解
beanValidationCore: true
beanValidationConstraints: true

安全配置

yaml
# OAuth2 配置
oauth2:
  flow: "accessCode"
  authorizationUrl: "https://auth.example.com/oauth/authorize"
  tokenUrl: "https://auth.example.com/oauth/token"
  scopes:
    read: "Read access"
    write: "Write access"

高级配置选项

预处理和后处理

yaml
# 启用后处理
enablePostProcessFile: true

# 预处理脚本
preprocessorScript: "./scripts/preprocess.js"

# 后处理脚本
postprocessorScript: "./scripts/postprocess.js"

自定义生成器

yaml
# 使用自定义生成器
customGeneratorClass: "com.company.CustomCodegen"

# 生成器 JAR 路径
generatorJarPath: "./custom-generator.jar"

扩展属性

yaml
# 自定义扩展属性
vendorExtensions:
  x-generator-version: "1.0.0"
  x-team: "API Team"
  x-documentation-url: "https://docs.example.com"

环境变量配置

bash
# 设置默认生成器
export OPENAPI_GENERATOR_DEFAULT_GENERATOR=spring

# 设置模板目录
export OPENAPI_GENERATOR_TEMPLATE_DIR=/path/to/templates

# JVM 选项
export JAVA_OPTS="-Xmx2048M -DlogLevel=debug"

# 代理设置
export HTTP_PROXY=http://proxy:8080
export HTTPS_PROXY=http://proxy:8080

配置文件示例

完整配置示例

yaml
# openapi-generator-config.yaml
generatorName: spring
inputSpec: ./api/openapi.yaml
outputDir: ./generated

# 全局属性
globalProperties:
  apis: true
  models: true
  supportingFiles: true
  apiTests: true
  modelTests: true

# 生成器配置
additionalProperties:
  basePackage: com.company.api
  modelPackage: com.company.api.model
  apiPackage: com.company.api.controller
  
  java8: true
  dateLibrary: java8
  useSpringBoot3: true
  
  useBeanValidation: true
  performBeanValidation: true
  
  documentationProvider: springdoc

# 类型映射
typeMappings:
  DateTime: OffsetDateTime
  Date: LocalDate

# 导入映射  
importMappings:
  OffsetDateTime: java.time.OffsetDateTime
  LocalDate: java.time.LocalDate

# 服务器变量
serverVariables:
  protocol:
    default: https
    enum:
      - http
      - https
  environment:
    default: production
    enum:
      - development
      - staging
      - production

# 自定义模板
templateDir: ./custom-templates

# 忽略文件
ignoreFileOverride: .openapi-generator-ignore

多环境配置

yaml
# config-dev.yaml
outputDir: ./generated/dev
additionalProperties:
  environment: development
  enableDebug: true
  logLevel: DEBUG

# config-prod.yaml  
outputDir: ./generated/prod
additionalProperties:
  environment: production
  enableDebug: false
  logLevel: INFO

命令行使用示例

基础使用

bash
# 最简单的使用
openapi-generator-cli generate \
  -i openapi.yaml \
  -g spring \
  -o ./generated

# 使用配置文件
openapi-generator-cli generate -c config.yaml

# 覆盖配置文件中的选项
openapi-generator-cli generate \
  -c config.yaml \
  -o ./custom-output \
  --additional-properties=basePackage=com.custom

高级使用

bash
# 组合多个配置
openapi-generator-cli generate \
  -i api.yaml \
  -g typescript-axios \
  -o ./client \
  -t ./templates \
  -c base-config.yaml \
  --additional-properties=npmName=@company/api-client \
  --type-mappings=DateTime=Date \
  --import-mappings=Date=Date \
  --global-property=apis,models \
  --skip-validate-spec

调试和故障排除

启用调试模式

bash
# 详细输出
openapi-generator-cli generate -v ...

# 调试模型
--global-property=debugModels

# 调试操作
--global-property=debugOperations

# 调试支持文件
--global-property=debugSupportingFiles

查看可用选项

bash
# 查看生成器列表
openapi-generator-cli list

# 查看生成器详情
openapi-generator-cli config-help -g spring

# 查看生成器支持的配置
openapi-generator-cli config-help -g spring --full-details

最佳实践

1. 版本控制配置文件

project/
├── openapi-config/
│   ├── base.yaml          # 基础配置
│   ├── dev.yaml           # 开发环境
│   ├── prod.yaml          # 生产环境
│   └── templates/         # 自定义模板

2. 使用配置继承

yaml
# base.yaml
$extends: ./defaults.yaml
generatorName: spring
inputSpec: ../api/openapi.yaml

# dev.yaml
$extends: ./base.yaml
outputDir: ./generated/dev
additionalProperties:
  environment: development

3. 脚本化配置

bash
#!/bin/bash
# generate.sh

ENVIRONMENT=${1:-dev}
CONFIG_FILE="./config/config-${ENVIRONMENT}.yaml"

openapi-generator-cli generate \
  -c "$CONFIG_FILE" \
  --additional-properties=buildTimestamp=$(date +%s)

总结

正确的配置能够:

  • 🎯 精确控制: 生成符合需求的代码
  • 🔧 灵活定制: 适应不同项目要求
  • 📦 标准化: 团队统一的生成标准
  • 🚀 提高效率: 减少手动调整工作

通过掌握这些配置选项,可以充分发挥 OpenAPI Generator 的强大功能。

SOLO Development Guide