本文介绍两种 Gradle 操作 dependency 的方式
关于 configuration、dependency 的理解,请见Gradle 理解:configuration、dependency
一、通过 configurations
通过 configurations.implementation 可以对依赖进行操作,不过只能进行查询、增、删,不能修改。
def implementations = configurations.getByName('implementation').dependencies
implementations.all {
println it
}
// 或直接
def implementations = configurations.implementation.dependencies
二、通过 resolutionStrategy
resolutionStrategy 用来定义依赖的处理策略。如:强制使用特定版本、替换、冲突解决、设置 snapshot 的超时时间等。
例如:
apply plugin: 'java' // 可以使用 java 提供的 configurations
configurations.all {
resolutionStrategy {
// 在依赖版本冲突时直接失败(包括间接传递的依赖)
failOnVersionConflict()
// 优先引用 build 之内的 modules,而不是外部依赖
preferProjectModules()
// 强制使用依赖的特定版本(包括间接传递的依赖)
// * 添加新的强制版本 module:
force 'asm:asm-all:3.3.1', 'commons-io:commons-io:1.4'
// * 替换存在的 module 为指定版本:
forcedModules = ['asm:asm-all:3.3.1']
// 选择依赖
componentSelection {
// 拒绝 RxJava 2.2.0
all { ComponentSelection selection ->
if (selection.candidate.module == 'rxjava' && selection.candidate.version == '2.2.0') {
selection.reject("bad version '2.2.0' for 'rxjava'")
}
}
// 拒绝 RxJava 2.2.0
withModule("io.reactivex.rxjava2:rxjava") { ComponentSelection selection ->
if (selection.candidate.version == "2.2.0") {
selection.reject("known bad version")
}
}
}
// 遍历依赖
eachDependency { DependencyResolveDetails details ->
// 为所有 'org.gradle' group 的依赖指定固定版本
if (details.requested.group == 'org.gradle') {
details.useVersion '1.4'
}
}
// 遍历依赖
eachDependency { details ->
// 修改 'groovy-all' 依赖为 'groovy'
if (details.requested.name == 'groovy-all') {
details.useTarget group: details.requested.group, name: 'groovy', version: details.requested.version
}
}
// 添加依赖替换规则
dependencySubstitution {
// 替换 module 为 project
substitute module('org.gradle:api') with project(':api')
// 替换 project 为 module
substitute project(':util') with module('org.gradle:util:3.0')
// 替换 module 2.0 为 module 2.1
substitute module('org.gradle:api:2.0') with module('org.gradle:api:2.1')
}
// 缓存动态版本 10 分钟
cacheDynamicVersionsFor 10*60, 'seconds'
// 不缓存改变中的 module
cacheChangingModulesFor 0, 'seconds'
}
}