Gradle 依賴&解決依賴沖突

# Gradle 依賴&解決依賴沖突

  • 如何定義一個依賴。
  • DependencyHandler,Dependency,Dependencies,Configuration,ConfigurationContainer 的關系。
  • 什么是傳遞依賴?
  • 如何定位依賴沖突?
  • 如何解決依賴沖突?
  • provided ,runtime 和 compile 三者區別?

# 如何定義依賴

在 Gradle 中常見的依賴類型有幾種有 3 種,下面一一列舉:

  • 方式1:依賴一個 project(或者說依賴一個 module)
  • 方式2:依賴一個 jar 包
  • 方式2:擴展:通過 fileTree 依賴 dir 文件夾下所有的 jar 包
  • 方式3:依賴遠程倉庫
dependencies {
    //方式1: 依賴一個名字為 "common" 的 project 
    compile project(":common")
    
    //方式2: 依賴一個本地 jar 包
    //依賴當前 module/libs/aliyun-vod-croe-android-sdk-1.0.0.jar
    compile files('libs/aliyun-vod-croe-android-sdk-1.0.0.jar')
    
    //方式2 擴展:通過 fileTree 指定 dir 依賴所有的 jar 包
    compile fileTree(dir: 'libs', include: ['*.jar'])
    
    //方式3: 依賴一個遠程倉庫的包
    compile 'com.android.support:appcompat-v7:26.1.0'
}

# DependencyHandler

當我們點擊 build.gradle 中的 compile 時,發現跟不進去源碼。那么是不是表示 compile 本不是類屬性或者方法呢?

compile 'com.android.support:appcompat-v7:26.1.0'

下面我們來分析一下,compile 是什么東西。

dependencies {
  compile 'com.android.support:appcompat-v7:26.1.0'
}

compile 是定義在 dependencies 塊中的,而 dependencies 是什么呢?下面來看看相關的源碼:

    1. project 的 dependencies 源代碼

通過閱讀注釋,可以知道 dependencies 接受的是一個 closure ,并且參數類型為 DependencyHandler 。那么要關注閉包具備的功能,那么就要關注 DependencyHandler 可以做什么事?

/**
 * <p>Configures the dependencies for this project.
 *
 * <p>This method executes the given closure against the {@link DependencyHand
 * DependencyHandler} is passed to the closure as the closure's delegate.
 *
 * <h3>Examples:</h3>
 * See docs for {@link DependencyHandler}
 *
 * @param configureClosure the closure to use to configure the dependencies.
 */
void dependencies(Closure configureClosure);
    1. 一組依賴的是如何表示的?

我們可以在 DependencyHandler 中找到下面這樣的定義方式,那么就可以明白,我們上面寫的 compile 對應于 configurationName ,而值就是對應于 dependencyNotation,我們可以將其看做是 key-value的關系,一組(configurationName,dependencyNotation)就表示一個 Configuration 對象。

dependencies {
    configurationName dependencyNotation1,dependencyNotation2
}
    1. 依賴底層的調用代碼

其實 DependencyHandler 源碼中有很多相關的方法,我這里列舉一個 add 方法,我們通過
compile 'com.android.support:appcompat-v7:26.1.0'其實底層應該調用就是 add 方法,對應的 configurationName 為 compile 而 dependencyNotation 就是 'com.android.support:appcompat-v7:26.1.0'

/**
 * Adds a dependency to the given configuration.
 *
 * @param configurationName The name of the configuration.
 * @param dependencyNotation
 *
 * The dependency notation, in one of the notations described above.
 * @return The dependency.
 */
Dependency add(String configurationName, Object dependencyNotation);

/**
 * Adds a dependency to the given configuration, and configures the dependency using the given closure.
 *
 * @param configurationName The name of the configuration.
 * @param dependencyNotation The dependency notation, in one of the notations described above.
 * @param configureClosure The closure to use to configure the dependency.
 * @return The dependency.
 */
Dependency add(String configurationName, Object dependencyNotation, Closure configureClosure);
    1. 通過add方法實現依賴

該方法的第三參數是一個閉包,它是對 Configuration 的一個配置,閉包類型是 ModuleDependency ,你可以在這里做一些你想要的配置,例如是支持傳遞依賴等,詳細可以查看ModuleDependency的源碼。

add('compile', 'org.hibernate:hibernate-core:3.6.3.Final')
        {
            ModuleDependency dependency ->
                //(1). 指定傳遞依賴
                //dependency.transitive = true
                
                //(2)exclude 對某一個庫排除傳遞依賴
                //exclude group: 'org.slf4j', module: 'slf4j-api'
        }
    1. 幾個相關類的關系圖

以下圖表示的是 Dependency,Dependencies,DependencyHandler,Configuration,ConfigurationContainer 的關系。

依賴關系

# 什么是傳遞依賴?

  • 圖示傳遞依賴

下面通過一個圖來表示傳遞依賴,如果 transitive 為 true 表示支持傳遞依賴,那么 projectC 將可以依賴 projectA 的內容,其中傳遞依賴是不好的,因為你無法確定被依賴的庫什么時候發生了更新,可能會因為更新,導致依賴失敗等問題,不過 Gradle 默認是傳遞依賴的。

傳遞依賴

# 如何定位依賴沖突?

  • 了解如何定位依賴沖突問題之前,我們先手動制造一個依賴沖突。

我們在 build.gradle 引入兩個依賴庫:

compile 'org.hibernate:hibernate-core:3.6.3.Final'
compile 'org.slf4j:slf4j-api:1.7.22'

執行一下命令查看依賴報告:

./gradlew :module:dependencies --configuration compile

Gradle 執行結果:

compile - Compile dependencies for 'main' sources (deprecated: use 'implementation' instead).
+--- org.hibernate:hibernate-core:3.6.3.Final
|    +--- antlr:antlr:2.7.6
|    +--- commons-collections:commons-collections:3.1
|    +--- dom4j:dom4j:1.6.1
|    +--- org.hibernate:hibernate-commons-annotations:3.2.0.Final
|    |    \--- org.slf4j:slf4j-api:1.5.8 -> 1.7.22(版本自動提升)
|    +--- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.0.Final
|    +--- javax.transaction:jta:1.1
|    \--- org.slf4j:slf4j-api:1.6.1 -> 1.7.22(版本自動提升)
\--- org.slf4j:slf4j-api:1.7.22

從上面的執行結果可以看出:Gradle 在構建時,默認會使用最高版本的庫,例如依賴 slf4j 最終都會以最高的版本為主。

  • Configuration 配置依賴問題

我們前面介紹過,每一個 dependency 依賴都是 Configuration ,那么我們可以遍歷ConfigurationContainer,獲取 每一個 Configuration 對象,然后處理對應的依賴沖突問題。

下面我們配置,當 Gradle 構建遇到依賴沖突時,就立即構建失敗:

configurations.all() {
    Configuration configuration ->
        //當遇到版本沖突時直接構建失敗
        configuration.resolutionStrategy.failOnVersionConflict()
}

在點擊 build 時,會出現如下錯誤:

Gradle依賴沖突

# 如何解決依賴沖突?

在上面依賴的兩個庫導致的依賴沖突是因為 slf4j 的版本不同導致的,那么我們知道原因之后就可以在依賴時指定不要傳入依賴某一個庫即可,下面來演示一下如何操作:

方式1:

  • 排除傳遞依賴
compile 'org.slf4j:slf4j-api:1.7.22'
compile ('org.hibernate:hibernate-core:3.6.3.Final'){
    //排除某一個庫(slf4j)依賴
    exclude group: 'org.slf4j',module: 'slf4j-api'
}
  • 下面就是排除傳遞依賴后的結果:
compile - Compile dependencies for 'main' sources (deprecated: use 'implementation' instead).
+--- org.slf4j:slf4j-api:1.7.22
\--- org.hibernate:hibernate-core:3.6.3.Final
     +--- antlr:antlr:2.7.6
     +--- commons-collections:commons-collections:3.1
     +--- dom4j:dom4j:1.6.1
     +--- org.hibernate:hibernate-commons-annotations:3.2.0.Final
     +--- org.hibernate.javax.persistence:hibernate-jpa-2.0-api:1.0.0.Final
     \--- javax.transaction:jta:1.1

  • 指定禁止傳遞依賴
compile('org.hibernate:hibernate-core:3.6.3.Final') {
    //指定禁止傳遞依賴
    transitive false
}
compile 'org.slf4j:slf4j-api:1.7.22'
  • 查看依賴報告
compile - Compile dependencies for 'main' sources (deprecated: use 'implementation' instead).
+--- org.hibernate:hibernate-core:3.6.3.Final
\--- org.slf4j:slf4j-api:1.7.22

方式2:

  • 當遇到依賴沖突時,指定一個版本號
configurations.all() {
    Configuration configuration ->
        configuration.resolutionStrategy.force(['org.slf4j:slf4j-api:1.6.1'])
        
        //或者這樣寫
        resolutionStrategy.setForcedModules(['org.slf4j:slf4j-api:1.6.1'])
}

# provided ,runtime 和 compile 三者區別?

compile : 依賴的包,編譯并打包到最終的 apk 文件中。

provided : 依賴的包只參與編譯而不會打包到最終的 apk 文件中。

runtime : 適用于依賴的包只作用在運行時而不需要在編譯時。

dependencies {
    //optional, help to generate the final application 
    provided('com.tencent.tinker:tinker-android-anno:1.9.1')
    //tinker's main Android lib
    compile('com.tencent.tinker:tinker-android-lib:1.9.1')
}

為應用生成 application 類,那么這個是一個 java 文件的生成,因此只需要在編譯階段去生成即可,而在運行時已經有這個生成的類了。

tinker依賴

# 總結

上面是我學習了 Grade 依賴相關知識后的一點點總結,通過了解 Gradle 的依賴,從而能正確的處理每一個庫的依賴關系。

記錄于 2018-08-13 晚

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,663評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,125評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,506評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,614評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,402評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,934評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,021評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,168評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,690評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,596評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,784評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,288評論 5 357
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,027評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,404評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,662評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,398評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,743評論 2 370

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,776評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,887評論 6 342
  • 說明 本文主要介紹和Gradle關系密切、相對不容易理解的配置,偏重概念介紹。部分內容是Android特有的(例如...
    jzj1993閱讀 15,679評論 1 62
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,596評論 25 707
  • 臘月廿八中午,父親載著我從火車北站回家,到小鎮的時候已經三點多了。 路過鎮上大橋的時候,卻看見橋已經沒了,夏天的洪...
    岳麥閱讀 522評論 0 1