AndroidStudio升級到3.0之后,gradle版本也隨之升級到了3.0.0版本。
classpath 'com.android.tools.build:gradle:3.0.0'
在新建一個Android工程的時候,build.gradle中的依賴默認為implementation,而不是之前的compile。另外,gradle 3.0.0版本以上,還有依賴指令api。本文主要介紹下implementation和api的區(qū)別。
新建工程默認生成的app的build.gradle文件中的依賴:
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
api 指令
完全等同于compile指令,沒區(qū)別,你將所有的compile改成api,完全沒有錯。
implementation指令
這個指令的特點就是,對于使用了該命令編譯的依賴,對該項目有依賴的項目將無法訪問到使用該命令編譯的依賴中的任何程序,也就是將該依賴隱藏在內(nèi)部,而不對外部公開。
簡單的說,就是使用implementation指令的依賴不會傳遞。例如,有一個module為testLib,testLib依賴于Glide:
implementation 'com.github.bumptech.glide:glide:3.8.0'
這時候,在testsdk里邊的java代碼是可以訪問Glide的。
另一個module為app,app依賴于testLib:
implementation project(':testLib')
這時候,因為testsdk使用的是implementation 指令來依賴Glide,所以app里邊不能引用Glide。
但是,如果testLib使用的是api來引用Glide:
api 'com.github.bumptech.glide:glide:3.8.0'
則與gradle3.0.0之前的compile指令的效果完全一樣,app的module也可以引用Glide,這就是api和implementation的區(qū)別。