首页 > 解决方案 > 是否可以阻止 Gradle 添加排除的传递依赖?

问题描述

我有一个使用 Gradle 5.6 构建的 Java 库,其中一些传递依赖被抑制

api('org.springframework.boot:spring-boot-starter-web') {
    exclude module: 'spring-boot-starter-logging'
    exclude module: 'spring-boot-starter-tomcat'
}

当我将它发布到 Maven 存储库时,我得到了相应的部分POM.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <scope>compile</scope>
        <exclusions>
            <exclusion>
                <artifactId>spring-boot-starter-tomcat</artifactId>
                <groupId>*</groupId>
            </exclusion>
            <exclusion>
                <artifactId>spring-boot-starter-logging</artifactId>
                <groupId>*</groupId>
            </exclusion>
        </exclusions>
    </dependency>
...
</dependencies>

但是当我也使用 Gradle 5.6 添加我的库作为依赖项时

dependencies {
    implementation 'my.group:my.lib:1.0.0'
}

我看到排除的依赖项(例如,spring-boot-starter-tomcat)出现在我的compileClasspath配置中。有没有办法一劳永逸地排除它,或者我应该在所有手动使用我的库的项目中这样做?

标签: javagradle

解决方案


如文档中所述(强调我的):

排除特定的传递依赖并不能保证它不会出现在给定配置的依赖中。例如,其他一些没有任何排除规则的依赖项可能会引入完全相同的传递依赖项。为了保证从整个配置中排除传递依赖,请使用每个配置的排除规则: Configuration.getExcludeRules()。事实上,在大多数情况下,配置每个依赖项排除的实际意图实际上是从整个配置(或类路径)中排除依赖项。

您可以将规则应用于所有配置,而不是为每个配置指定排除规则:

// Kotlin DSL
configurations.all {
    exclude(mapOf("module" to "spring-boot-starter-logging"))
    exclude(mapOf("module" to "spring-boot-starter-tomcat"))
}

推荐阅读