如何将本地的 .jar 文件添加到 build.gradle.kt 文件的依赖中?

49

我已经阅读了有关build.gradle的类似问题,并浏览了Gradle Kotlin Primer,但我不知道如何在build.gradle.kt文件中添加.jar文件。我试图避免使用mavenLocal()。

3个回答

94

如果您正在寻找的是相当于

implementation fileTree(dir: 'libs', include: ['*.jar'])

那将是:

implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))

4
请详细说明如何添加带有绝对路径的单个 Jar 文件。 - Haha TTpro
1
你有没有任何能够让这一切更明显的参考文献? - undefined
1
你有没有任何能够让这一切更明显的参考文献? - Gleichmut

26

对于使用 build.gradle.kts 的 Gradle 5.4.1 中的 Kotlin dsl,请使用:

use

implementation(files("/commonjar/3rdparty/gson-2.8.5.jar"))

我建议一次添加单个文件,因为这样更容易跟踪依赖关系。

build.gradle.kts 的完整内容如下:

plugins {
    // Apply the java-library plugin to add support for Java Library
    `java-library`
}

repositories {
    // Use jcenter for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

configurations { create("externalLibs") }



dependencies {
    // This dependency is exported to consumers, that is to say found on their compile classpath.
    api("org.apache.commons:commons-math3:3.6.1")

    // This dependency is used internally, and not exposed to consumers on their own compile classpath.
    implementation("com.google.guava:guava:27.0.1-jre")

    implementation(files("/commonjar/3rdparty/gson-2.8.5.jar"))


    // Use JUnit test framework
    testImplementation("junit:junit:4.12")
}

4
最好指定完整路径,即implementation(files("$projectDir/commonjar/3rdparty/gson-2.8.5.jar")),而不是使用相对路径。我在Travis-CI上使用相对路径时遇到了错误。 - gotson

12

另一篇答案建议像在Groovy中通常做的那样使用映射键和值。与使用动态方法相反,一种更符合惯用法且类型安全等效的方法是使用闭包过滤要包含在文件树中的文件:

api(fileTree("src/main/libs") { include("*.jar") })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接