如何在Gradle多模块Android项目中避免重复配置子项目依赖?
解决Gradle多模块Android项目的依赖重复问题(遵循DRY原则)
嘿,我完全懂你这种被重复代码烦到的感觉——两个子模块的build.gradle里一堆一模一样的依赖声明,改起来要改两次,太容易出错了。下面给你几个实用的方案,帮你把这些重复代码彻底干掉:
方案1:用根项目扩展属性 + 共享Gradle脚本(最贴合现有习惯)
这个方案适配你当前使用rootProject.ext的方式,步骤清晰易上手:
第一步:在根项目build.gradle统一管理依赖版本(可选但推荐)
先把所有依赖的版本号集中放在根项目的扩展属性里,后续升级版本只需要改一处:
// 根项目 build.gradle ext { // 统一管理版本号 timberVersion = "5.0.1" glideVersion = "4.16.0" coreKtxVersion = "1.12.0" // 直接定义完整依赖坐标 timber = "com.jakewharton.timber:timber:$timberVersion" glide = "com.github.bumptech.glide:glide:$glideVersion" glideCompiler = "com.github.bumptech.glide:compiler:$glideVersion" coreKtx = "androidx.core:core-ktx:$coreKtxVersion" }
第二步:创建共享依赖脚本
在项目根目录新建gradle文件夹(如果没有的话),然后创建shared-app-dependencies.gradle文件,把两个子项目重复的依赖内容迁移过来:
// gradle/shared-app-dependencies.gradle dependencies { // 所有子项目共享的基础依赖 implementation rootProject.ext.timber implementation rootProject.ext.glide annotationProcessor rootProject.ext.glideCompiler implementation rootProject.ext.coreKtx // 共享的测试依赖也可以放这儿 testImplementation "junit:junit:4.13.2" androidTestImplementation "androidx.test.ext:junit:1.1.5" }
第三步:在子项目中应用共享脚本
打开每个子项目的build.gradle,删掉原来重复的依赖块,在文件末尾添加:
// 子项目 build.gradle apply from: rootProject.file("gradle/shared-app-dependencies.gradle") // 保留子项目独有的依赖 dependencies { // 比如这个子项目特有的业务SDK implementation "com.example:custom-business-sdk:1.0.0" }
方案2:使用Gradle Version Catalog(更现代的官方推荐方式)
如果你的Gradle版本在7.0以上,推荐用官方推出的Version Catalog来管理依赖,它比ext更规范,还支持IDE自动提示:
第一步:创建libs.versions.toml文件
在项目根目录的gradle文件夹下新建这个文件,内容如下:
[versions] timber = "5.0.1" glide = "4.16.0" coreKtx = "1.12.0" [libraries] timber = { group = "com.jakewharton.timber", name = "timber", version.ref = "timber" } glide = { group = "com.github.bumptech.glide", name = "glide", version.ref = "glide" } glide-compiler = { group = "com.github.bumptech.glide", name = "compiler", version.ref = "glide" } core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } [bundles] app-shared = ["timber", "glide", "core-ktx"]
这里的bundles可以把一组共享依赖打包成集合,引用起来更简洁。
第二步:在子项目中引用共享依赖
子项目的build.gradle里可以这样写:
dependencies { // 一键引用整个共享依赖包 implementation libs.bundles.app.shared annotationProcessor libs.glide.compiler // 子项目独有的依赖 implementation "com.example:custom-business-sdk:1.0.0" }
方案3:用根项目subprojects块(适合所有子项目依赖高度一致的场景)
如果你的两个子项目都是应用模块,且绝大多数依赖完全相同,也可以在根项目build.gradle中用subprojects块统一配置:
// 根项目 build.gradle subprojects { // 只针对应用模块生效 if (plugins.hasPlugin("com.android.application")) { dependencies { implementation rootProject.ext.timber implementation rootProject.ext.glide // 其他共享依赖... } } }
不过这个方案灵活性稍差,若后续某个子项目需要移除某个共享依赖,调整起来会比较麻烦,所以更推荐前两个方案。
不管选哪个方案,都能帮你彻底解决依赖重复的问题,以后改依赖只需要在一处修改,完全符合DRY原则!
内容的提问来源于stack exchange,提问作者treesAreEverywhere
相关产品推荐
相关产品推荐

