Gradle依賴排除

2021-08-31 16:34:55 字數 1806 閱讀 2742

在引用依賴時經常會有這樣的問題:某些間接引用的依賴項是不需要的;產生了依賴衝突。此時需要排除一些依賴。

下面的內容介紹了幾種在gradle中排除依賴的方式。

在dependency中排除

dependencies {

compile('com.zhyea:ar4j:1.0') {

//excluding a particular transitive dependency:

exclude module: 'cglib' //by artifact name

exclude group: 'org.jmock' //by group

exclude group: 'org.unwanted', module: 'iambuggy' //by both name and group

這種方式是粒度最細的,也是最為繁瑣的。此時可以考慮全域性設定。

在全域性配置中排除

全域性配置是在configuration中完成的。

configurations {

compile.exclude module: 'cglib'

all*.exclude group:'org.unwanted', module: 'iambuggy'

禁用傳遞依賴

禁用傳遞依賴需要將屬性transitive設定為false。可以在dependency中禁用傳遞依賴,也可以在configuration中全域性禁用:

compile('com.zhyea:ar4j:1.0') {

transitive = false

configurations.all {

transitive = false

還可以在單個依賴項中使用@jar識別符號忽略傳遞依賴:

compile 'com.zhyea:ar4j:1.0@jar'

強制使用某個版本

如果某個依賴項是必需的,而又存在依賴衝突時,此時沒必要逐個進行排除,可以使用force屬性標識需要進行依賴統一。當然這也是可以全域性配置的:

compile('com.zhyea:ar4j:1.0') {

force = true

configurations.all {

resolutionstrategy {

force 'org.hamcrest:hamcrest-core:1.3'

在打包時排除依賴

先看乙個示例:

task zip(type: zip) {

into('lib') {

from(configurations.runtime) {

exclude '*unwanted*', '*log*'

into('') {

from jar

from 'doc'

**表示在打zip包的時候會過濾掉名稱中包含「unwanted」和「log」的jar包。這裡呼叫的exclude方法的引數和前面的例子不太一樣,前面的引數多是map結構,這裡則是乙個正規表示式字串。

也可以使用在打包時呼叫include方法選擇只打包某些需要的依賴項:

task zip(type: zip) {

into('lib') {

from(configurations.runtime) {

include '*ar4j*', '*spring*'

into('') {

from jar

from 'doc'

始終選擇最新的依賴的項

最後這個特性和排除依賴沒有什麼關係,只是順帶說一下。

示例如下:

compile 'com.zhyea:ar4j:+'

就這樣。

Gradle依賴排除

在引用依賴時經常會有這樣的問題 某些間接引用的依賴項是不需要的 產生了依賴衝突。此時需要排除一些依賴。下面的內容介紹了幾種在gradle中排除依賴的方式。在dependency中排除 dependencies compile com.zhyea ar4j 1.0 excluding a partic...

gradle 配置全域性依賴排除

gradle官網上說明 每個依賴項都有不同的作用範圍,如果想要配置可以使用configurations選項配置.圖1.configurations宣告的依賴項用於特定目的 1 1使用groovy語言是配置gradle全域性排除依賴 configurations.all configurations ...

Gradle檢視依賴及排除依賴的方法

f sts4 order test gradlew order test api dependencies configuration compile aa.txt 檢視全部的依賴,同時寫入檔案bb.txt f sts4 order test gradlew order test api depen...