Gradle依赖管理

来源:互联网 发布:python发送http请求 编辑:程序博客网 时间:2024/05/17 10:04

Gradle依赖库缓存

Gradle拉取的aar库保存在本地的~/.gradle文件夹和~/.m2文件夹中。由于早期版本的Gradle在缓存的处理上有些问题,有时会出现aar更新后无法生效的问题,可以通过删除上面缓存的方式进行修复。

利用Gradle的通知机制

虽然当项目依赖库有更新之后,Gradle并不会立即通知主项目,但Gradle会给出一种通知机制,即利用Gradle的检查周期进行check。
configurations.all {    resolutionStrategy.cacheChangingModulesFor(0,'seconds')}

详细的官方文档可以参考下面的网址:
https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

同时Gradle还提供了在依赖传递中强制刷新配置。

 dependencies {    compile 'com.android.support:multidex:1.0.1'{        transitive = true    }}

如果增加一个transitive属性并设置其值为true,则会强制刷新远程库。

利用Gradle的依赖检查

利用Gradle提供的task可以很方便的解决依赖问题,使用Gradle指令gradle androidDependencies,可以方便地找到每种buildType下的依赖关系图。

Gradle依赖传递

在使用Gradle aar文件时,会产生依赖库的传递,如A依赖B,B依赖C。正常使用项目B时的写法:

 dependencies {    compile 'com.xxx.xxx.xxx:1.0.0'}

但如果只想依赖B,而不依赖C,不传递依赖,写法为:

 dependencies {    compile 'com.xxx.xxx.xxx:1.0.0@aar'}

另外可以使用exclude module排除一个库中引用的其他库。

 dependencies {    compile ('com.xxx.xxx.aaa:1.0.0') {        exclude module:'com.xxx.xxx.bbb:1.0.0'        exclude module:'com.xxx.xxx.ccc:1.0.0'    }}

这样可以在A库中去除B库和C库的依赖。

Gradle依赖统一管理

Gradle引用依赖非常简单,但一旦涉及多module,每个module的依赖管理就变得非常复杂,使用Gradle全局变量就可以方便的实现管理。
在根目录的build.gradle脚本中配置如下代码:

 ext {     android = [compileSdkVersion:23,                 buildToolsVersion:'23.0.2']    dependencies = [supportv7:'com.android.support:appcompat-v7:23.2.0'] }

在每个module中,可以通过代码使用全局的依赖配置:

    android {        comlileSdkVersion rootProject.ext.android.compileSdkVersion        buildToolsVersion rootProject.ext.android.buildToolsVersion    }    dependencies {        compile rootProject.ext.dependencies.supportv7    }

当然可以直接在根目录下创建一个config.gradle文件,添加如下代码:

 ext {    android = [compileSdkVersion:23,                 buildToolsVersion:'23.0.2']    dependencies = [supportv7:'com.android.support:appcompat-v7:23.2.0'] }

在根目录的build.gradle文件中添加:

    apply from:'config.gradle'

这样就可以在所有的子module中使用这些参数了,使用方法同上。

0 0
原创粉丝点击