You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI 3.0 Gradle项目如何为Swagger Codegen指定templateDir

Swagger Codegen v3 指定自定义模板目录的解决方案

Swagger Codegen v3 中CodegenConfig类没有单独的setTemplateDir方法,你需要把模板路径配置放到ClientOpts的属性列表中,修改后的代码如下:

task generateServer {
        doLast {
            def openAPI = new OpenAPIV3Parser().read(rootProject.swaggerFile.toString(), null, null)
            def clientOpts = new ClientOptInput().openAPI(openAPI)
            def codegenConfig = CodegenConfigLoader.forName('spring')
            codegenConfig.setOutputDir(project.buildDir.toString())

            clientOpts.setConfig(codegenConfig)
            def clientOps = new ClientOpts()
            clientOps.setProperties([
                    'dateLibrary'     : 'java8', // Date library to use
                    'useTags'         : 'true',  // Use tags for the naming
                    'interfaceOnly'   : 'true',   // Generating the Controller API interface and the models only
                    'templateDir'     : rootProject.file('templates/spring').absolutePath // 替换为你实际的模板目录路径,建议用绝对路径避免识别异常
            ])

            clientOpts.setOpts(clientOps)

            def generator = new DefaultGenerator().opts(clientOpts)
            generator.generate() // Executing the generation
        }
    }

额外注意事项

  • 模板目录需要和你使用的生成器对应,比如你用spring生成器,就需要把对应的mustache模板放到你指定的目录下,不需要修改的模板可以不用复制,生成器会自动 fallback 到内置模板
  • 路径建议用项目根目录定位的绝对路径,避免相对路径因为Gradle执行上下文变化导致找不到模板
  • 如果你只需要修改部分模板,仅保留你修改过的模板文件即可,其他未修改的模板会自动使用官方内置版本

内容的提问来源于stack exchange,提问作者xWAV92OdD445CbzcZAEyunk2M06fJi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 13:54:05