首页 > 解决方案 > Spring-boot 项目,使用 Gradle,使用 Kotlin 编码,自动生成 OpenAPI kotlin 类

问题描述

问题:生成的源没有被 gradle 拾取为源的一部分,因此导入生成的接口失败。

问题:如何添加生成的源代码以便 gradle(带有 goovy dsl 和 kotlin 插件)获取它们?

设置:spring-boot -> kotlin 编程语言 gradle -> groovy

我可以毫无问题地使用OpenAPI Generator Gradle Plugin生成 kotlin 类。

我正在使用“interfaceOnly”选项,所以它只创建接口。这意味着我确实需要实施这些。

我正在使用典型的 gradle 项目设置。现在我不知道将生成的文件放在哪里,以便 gradle(和 intellj)拾取它们。

开放API.yaml:

openapi: 3.0.1
info:
  version: 0.1.0
  title: Villagechatter Calendar
  description: Villagechatter calendar microservice

tags:
  - name: external
    description: external API
  - name: internal
    description: Internal API for other microservices

paths:
  /hello:
    get:
      responses:
        200:
          description: Ok
          content:
            text/plain:
              schema:
                type: string
                description: demo
                example: Hello World!

构建.gradle:

    id("org.springframework.boot") version "2.3.1.RELEASE"
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    id "org.jetbrains.kotlin.jvm" version "1.3.72"
    id "org.openapi.generator" version "4.3.1"
}
apply plugin: 'kotlin'

group = "com.example"
version = "0.0.1-SNAPSHOT"

repositories {
    mavenCentral()
}

compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}


openApiGenerate {
    inputSpec = "$rootDir/specs/openApi.yaml"
    generatorName = "kotlin-spring"
    //setting package names and interface only with a configFile, should not matter for the problem
    outputDir = "$buildDir/generated-src"
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude group : "org.junit.vintage"
        exclude module : "junit-vintage-engine"
    }
}

我尝试过的:

sourceSets {
    main {
        kotlin.srcDirs += "PATH-TO-GENERATED-FILES"
    }
}

还尝试创建一个新的 sourceSet 并将其添加到 compileKotlin 任务中

我找到的谷歌结果都是关于 gradle 和 kotlin dsl 的,对不起,如果这是重复的,我还没有找到解决方案。

标签: spring-bootkotlingradleopenapi-generator

解决方案


您是否尝试自动生成它们并将它们用作项目中的源?为什么不直接将它们生成到项目目录中呢?

outputDir = "$projectDir"


推荐阅读