傳統(tǒng)的依賴管理
過去通過gradle的ext屬性來維護(hù)依賴庫一個map
ext {
dependencies = [
"appcompat" : "androidx.appcompat:appcompat:1.2.0",
"recyclerview" : "androidx.recyclerview:recyclerview:1.2.0",
]
}
然后再相應(yīng)的module中添加具體的引用
implementation rootProject.ext.dependencies[appcompat]
implementation rootProject.ext.dependencies[recyclerview]
這種方法實(shí)現(xiàn)了依賴庫的集中管理,但是缺少IDE的支持在添加依賴庫的時(shí)候IDE不能自動補(bǔ)全
buildSrc方式管理依賴庫
- 什么是buildSrc
當(dāng)你運(yùn)行Gradle時(shí),它會檢查項(xiàng)目中是否存在一個名為buildSrc的目錄。
然后Gradle會自動編譯并測試這段代碼,并將其放入構(gòu)建腳本的類路徑中。您不需要提供任何進(jìn)一步的操作提示。
- 使用buildSrc
- 創(chuàng)建與app同級的文件夾buildSrc
- 在buildSrc文件夾里創(chuàng)建名為build.gradle.kts的文件,并添加如下代碼
plugins {
`kotlin-dsl`
}
repositories {
mavenCentral()
}
-
在buildSrc的module中創(chuàng)建src、main、java文件夾,目錄格式如下圖
微信截圖_20210716154051.png 在java目錄中創(chuàng)建類Deps.kt 并添加相應(yīng)的依賴管理
object V{
const val appcompat="1.2.0"
const val retrofit="2.9.0"
const val material="1.3.0"
}
object Deps {
const val appcompat= "androidx.appcompat:appcompat:${V.appcompat}"
const val retrofit= "com.squareup.retrofit2:retrofit:${V.retrofit}"
const val material= "com.google.android.material:material:${V.material}"
}
- 在具體的mudole中引用
mudole_one/build.gradle
dependencies {
implementation Deps.appcompat
implementation Deps.material
implementation Deps.retrofit
}
mudole_two/build.gradle
dependencies {
implementation Deps.appcompat
implementation Deps.material
implementation Deps.retrofit
}
最終實(shí)現(xiàn)如下效果

動畫.gif
總結(jié)
buildSrc 方式管理依賴大大增加了依賴管理的便捷性和易用性
優(yōu)點(diǎn)
- 共享 buildSrc 庫工件的引用,全局管理依賴
- 支持 AndroidStudio 自動補(bǔ)全,實(shí)現(xiàn)Autocomplete
- 支持依賴庫的點(diǎn)擊跳轉(zhuǎn)
缺點(diǎn)
A change in buildSrc causes the whole project to become out-of-date.
Thus, when making small incremental changes, the --no-rebuild command-line option is often helpful to get faster feedback.
Remember to run a full build regularly or at least when you’re done, though.
buildSrc的更改會導(dǎo)致整個項(xiàng)目過時(shí),因此,在進(jìn)行小的增量更改時(shí),
-- --no-rebuild命令行選項(xiàng)通常有助于獲得更快的反饋。不過,請記住要定期或至少在完成后運(yùn)行完整版本
- 缺點(diǎn)就是buildSrc 依賴更新將重新構(gòu)建整個項(xiàng)目
