iT邦幫忙

2023 iThome 鐵人賽

DAY 22
0

Day 21 提到解決依賴項解析衝突的 3 個辦法。

接著來看官方文件對解法之一的依賴項約束 (dependency constraints)說明。

Dependency constraints allow you to define the version or the version range of both dependencies declared in the build script and transitive dependencies. It is the preferred method to express constraints that should be applied to all dependencies of a configuration. When Gradle attempts to resolve a dependency to a module version, all dependency declarations with version, all transitive dependencies and all dependency constraints for that module are taken into consideration. The highest version that matches all conditions is selected. If no such version is found, Gradle fails with an error showing the conflicting declarations. If this happens you can adjust your dependencies or dependency constraints declarations, or make other adjustments to the transitive dependencies if needed. Similar to dependency declarations, dependency constraint declarations are scoped by configurations and can therefore be selectively defined for parts of a build. If a dependency constraint influenced the resolution result, any type of dependency resolve rules may still be applied afterwards.

對依賴項使用 constraints {} 區塊,可讓你定義傳遞依賴項 (transitive dependencies)、構建腳本 (build script)中宣告依賴項的版本與版本範圍。它是用來把限制 (constraints) 套用到所有依賴項設置的首選方法。

當 Gradle 嘗識解析模組版本 (module version) 的依賴項時,所有帶有版本號的依賴項、模組上的所有傳遞依賴項 (transitive dependencies)以及所有依賴項約束 (dependency constraints) 都會被納入 Gradle 解析過程。

這過程中,會選擇符合所有條件的最高版本。如果找不出這樣的版本,Gradle 會拋出構建錯誤,表示此時有依賴項衝突發生。在此情形,你可以調整你的依賴項或依賴項約束 (dependency constraints),或是對傳遞依賴項做出必要的調整。

與宣告依賴項相似的是,宣告依賴項約束 (dependency constraints) 的效力範圍由配置 (configurations) 決定。因此可以選擇性地為構建做出部份界定。

當依賴項約束 (dependency constraints)影響到解析結果,接下來的過程依然能繼續適用任何種類的依賴項解析規則。

資料來源
Gradle - Adding constraints on transitive dependencies


上一篇
[Day 21] 認識依賴項解析 (Dependency Resolution)
下一篇
[Day 23] 依賴項衝突的場景
系列文
[Android] 怎麼蓋地基?論 build.gradle 與它的快樂夥伴們30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言