Gradle 技巧:操作 dependency

14 篇文章 1 订阅

本文介绍两种 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'
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值