冰雹多模块项目中的依赖管理

图片

参赛作品


本文着眼于原生android项目,但由于gradle原则上是通用的汇编系统,因此它适用于gradle可以收集的其他项目。 这个想法不是我的,我来自Jake Wharton SdkSearch的github项目-一组用于搜索android sdk文档的程序。

问题


如果不使用库,现代应用程序几乎是不可能(不切实际)编写的。 随着依赖性的出现,出现了管理版本控制的任务。 也许对于中间人的单模块android应用程序来说这不是问题,然后在具有代码重用的较大项目中,这个问题是相关的。 尤其是在对支持 androidx库的版本控制中,其版本控制超出了合理范围,您只需查看AndroidX版本即可

解决方案


由于具有如此多的依赖关系,因此所有模块都依赖于该库的一个版本非常重要,否则在最意外的地方会出现运行时的意外情况。
Gradle使用groovy作为脚本语言,结合动态类型,提供了一种方便的方式来组织依赖项管理。

在DSL等级中,您可以使用ext ExtraPropertiesExtension对象将属性添加到项目中。 另外,在模块脚本中,您可以访问项目脚本(根模块),该脚本允许您在根脚本中声明依赖项的所有版本,并且您已经可以从内部的任何模块中引用它们。

例如,让我们的android应用程序使用依赖项:kotlin,kotlin stdlib,kotlin junit,facebook sdk,androidx,google material

根build.gradle:

buildscript { ext { versions = [ 'kotlin': '1.3.50', 'fb': '4.40.0' ] deps = [ 'kotlin': [ 'stdlib': [ 'jdk': "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${versions.kotlin}" ], 'test': [ 'common': "org.jetbrains.kotlin:kotlin-test-common:${versions.kotlin}", 'annotations': "org.jetbrains.kotlin:kotlin-test-annotations-common:${versions.kotlin}", 'jdk': "org.jetbrains.kotlin:kotlin-test-junit:${versions.kotlin}" ] ], 'androidx' : [ 'annotation': "androidx.annotation:annotation:1.1.0", 'appCompat': 'androidx.appcompat:appcompat:1.1.0', 'constraintLayout': 'androidx.constraintlayout:constraintlayout:1.1.3', 'ktx': 'androidx.core:core-ktx:1.1.0', 'dynamicAnimation': 'androidx.dynamicanimation:dynamicanimation:1.0.0', 'gridLayout': 'androidx.gridlayout:gridlayout:1.0.0', 'localBroadcastManager': 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0', 'multidex': 'androidx.multidex:multidex:2.0.1', 'recyclerView': 'androidx.recyclerview:recyclerview:1.1.0-beta04' ], 'material': 'com.google.android.material:material:1.0.0', 'fb': [ 'core': "com.facebook.android:facebook-core:${versions.fb}", 'login': "com.facebook.android:facebook-login:${versions.fb}", 'share': "com.facebook.android:facebook-share:${versions.fb}" ] ] repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.0-alpha11' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${versions.kotlin}" } } 

要点:
如果多个依赖项具有一个版本(例如,一个大型SDK的一部分),则该版本将添加到版本属性中,例如Kotlin和Facebook的版本。 如果依赖关系是单行形式,例如google material,那么制作版本是不切实际的。 不需要删除androidx库的版本,因为 Google拒绝将版本彼此对齐以加快单个库的发布速度。

作为此定义的结果,在所有子模块中,依赖项的声明成为简洁的层次结构,没有版本控制,因为 现在,所有模块都依赖于相同的库版本。

build.gradle中模块依赖项部分的示例

 dependencies { implementation deps.kotlin.stdlib.jdk implementation deps.androidx.appCompat implementation deps.androidx.browser implementation deps.androidx.cardView implementation deps.androidx.constraintLayout implementation deps.androidx.ktx implementation deps.androidx.multidex implementation deps.androidx.recyclerView implementation deps.material implementation deps.fb.core implementation deps.fb.login implementation deps.fb.share testImplementation deps.kotlin.test.jdk } 

发生了什么-模块的库版本消失了,库的层次结构出现了
还值得注意的是,该模块不必依赖于根脚本中描述的所有库,而仅依赖于那些必需的库。

正如我上面提到的,使用这种方案的工作草案在这里

Source: https://habr.com/ru/post/zh-CN468959/


All Articles