如何使用 Gradle 和 Kotlin DSL 创建额外的 Kotlin SourceSet

xen*_*ide 4 gradle kotlin gradle-kotlin-dsl

我想创建一个测试库源集,src/tlib/kotlin它“位于” main 和 test之间。我有这个,但我不确定为什么我会java为 kotlin使用源目录,我需要根据我的主要来源获取它

sourceSets {
   create("tlib").java.srcDir("src/tlib/kotlin")
}
Run Code Online (Sandbox Code Playgroud)

更新

Calebs-MBP:phg-entity calebcushing$ ./gradlew build
e: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class phg.entity.AbstractEntityBase, unresolved supertypes: org.springframework.data.domain.Persistable
> Task :compileTlibKotlin FAILED
Run Code Online (Sandbox Code Playgroud)

关闭

sourceSets {
    val main by getting
    val tlib by creating {
        java {
            srcDir("src/tlib/kotlin")
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
    }
    val test by getting {
        java {
            compileClasspath += tlib.output
            runtimeClasspath += tlib.output
        }
    }
}

configurations {
    val compile by getting
    val runtime by getting
    val tlibCompile by getting {
        extendsFrom(compile)
    }
    val tlibRuntime by getting {
        extendsFrom(runtime)
    }
    val testCompile by getting {
        extendsFrom(tlibCompile)
    }
    val testRuntime by getting {
        extendsFrom(tlibRuntime)
    }
}

dependencies {
    implementation("${project.group}:constant:[0.1,1.0)")
    api("javax.validation:validation-api")
    api("javax.persistence:javax.persistence-api")
    api("org.springframework.data:spring-data-commons") // has the missing dependency
Run Code Online (Sandbox Code Playgroud)

Lou*_*met 6

许多事情都由插件妥善处理,因此添加的内容实际上是关于配置 sourceSet 类路径和接线配置。

这是一个简短的回答,显示了类路径配置和一个配置扩展:

sourceSets {
    val tlib by creating {
        // The kotlin plugin will by default recognise Kotlin sources in src/tlib/kotlin
        compileClasspath += sourceSets["main"].output
        runtimeClasspath += sourceSets["main"].output
    }
}

configurations {
    val tlibImplementation by getting {
        extendsFrom(configurations["implementation"])
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 较新版本的 Gradle 具有类型安全访问器,因此现在您可以执行 `sourceSets.main.get().output` 和 `extendsFrom(configurations.implementation.get())`。 (2认同)