对相同类型的依赖项进行分组的推荐方法是什么?

What is the recommended way to group dependencies of the same type?

我想按类型分离我的项目中的依赖项,并且正在考虑通过以下方式这样做:

// Implementation dependencies
dependencies {
    implementation("foo:bar:1") {
        because("reason 1")
    }

    implementation("foo:bar:2") {
        because("reason 2")
    }

    implementation("foo:bar:3") {
        because("reason 3")
    }
}

// Test implementation dependencies
dependencies {
    testImplementation("foo:bar:4") {
        because("reason 4")
    }

    testImplementation("foo:bar:5") {
        because("reason 5")
    }
}

问题:

  1. 通过这种方式构造构建文件后,我可以构建项目,但是我没有看到任何权威资料表明正式支持指定多个dependencies块。有这样的素材吗?

  2. 有没有比这更可取的按类型分离依赖的方法?最好,我希望每个模块都有一个依赖配置(implementationtestImplementation 等),以便记录包含每个模块的原因,就像上面的配置一样。

I don't see any authoritative material stating that specifying multiple dependencies blocks is formally supported. Does such material exist?

不需要任何 material 因为 Gradle DSL(Groovy 或 Kotlin)没有什么特别或神奇的。简直就是 Gradle API.

的甜头

指定多个 dependencies 块是完全合法的。如果你要对 Gradle DSL 进行去糖化处理,调用多个 dependencies 块实际上只是在做:

project.getDependencies().add("implementation", "foo:bar:1")
project.getDependencies().add("testImplementation", "foo:bar:4")

这与简单地多次调用 List 上的 add(...) 方法没有什么不同。

Is there a more preferable way of separating dependencies by type than this?

创建一个将依赖项捆绑在一起的库(项目或子项目)。使用 Java Library Plugin 可以轻松完成此操作。例如,对于您的测试库:

dependencies {
    api("foo:bar:4") {
        because("reason 4")
    }
    api("foo:bar:5") {
        because("reason 5")
    }
}

然后只需在您的主项目中使用该库即可:

dependencies {
    testImplementation(project(":my-test-library")) {
        because("bundles test libs")
    }
}

没有这样的支持,我认为也不需要,但是为了满足您的要求,我们可以创建一个扩展函数来区分不同的依赖项。无论如何,许多 Kotlin DSL 只是扩展函数,所以添加如下内容。只需在您的 buildSrc Dependencies.kts 文件或任何您喜欢但应该可以全局访问的地方声明它。

// test
    fun Project.dependenciesTest(configuration: DependencyHandlerScope.() -> Unit) =
        DependencyHandlerScope.of(dependencies).configuration()

//app
    fun Project.dependenciesApp(configuration: DependencyHandlerScope.() -> Unit) =
        DependencyHandlerScope.of(dependencies).configuration()

现在在调用站点中这样调用。

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

dependenciesTest {
    testImplementation(AppDependencies.junit)
}