用兼容的替换替换依赖模块

时间:2018-05-23 21:25:49

标签: gradle-kotlin-dsl

在Gradle Groovy DSL中,您可以轻松substitute a dependency module with a compatible replacement,如Gradle user manual中所述。你如何在Gradle Kotlin DSL中做同样的事情?

2 个答案:

答案 0 :(得分:2)

TLDR

Gradle Kotlin DSL中Gradle docs的示例

configurations.forEach({c: Configuration ->
    println("Inside 'configurations.forEach'")

    val replaceGroovyAll: DependencyResolveDetails.() -> Unit = {
        println("Inside 'replaceGroovyAll'")
        if (requested.name == "groovy-all") {
            val targetUsed = "${requested.group}:groovy:${requested.version}"
            println("Replacing 'groovy-all' with $targetUsed")
            useTarget(targetUsed)
            because("prefer 'groovy' over 'groovy-all'")
        }
        if (requested.name == "log4j") {
            val targetUsed = "org.slf4j:log4j-over-slf4j:1.7.10"
            println("replacing 'log4j' with $targetUsed")
            useTarget(targetUsed)
            because("prefer 'log4j-over-slf4j' 1.7.10 over any version of 'log4j'")
        }
    }
    c.resolutionStrategy.eachDependency(replaceGroovyAll)
})

详细

Gradle&#39; ResolutionStrategy.eachDependency接受Action<? super DependencyResolveDetails>类型的参数。 Since version 0.8.0 Kotlin Gradle DSL将Action转换为Function literal with receiver。因此,无论何时需要在Groovy Gradle脚本中传递Action<T>,您都可以在Kotlin中将其定义为

val funcLit: T.() -> Unit = {
    // fields and methods of T are in scope here
}

然后,您可以将此funcLit作为参数传递给Action<T>

答案 1 :(得分:0)

我还在项目的github上打开了一个issue,由Github用户eskatos回答。我编码并执行了他的答案,发现它也有效。这是他的代码。

configurations.all {
    resolutionStrategy.eachDependency {
        if (requested.name == "groovy-all") {
            useTarget("${requested.group}:groovy:${requested.version}")
            because("prefer 'groovy' over 'groovy-all'")
        }
        if (requested.name == "log4j") {
            useTarget("org.slf4j:log4j-over-slf4j:1.7.10")
            because("prefer 'log4j-over-slf4j' 1.7.10 over any version of 'log4j'")
        }
    }
}