在 Gradle 中排除隐藏依赖项的最佳方法是什么?

Whats the best way to exclude burried dependencies in Gradle?

例如,您在 Gradle 项目的依赖项中看到:

+--- org.springframework.security:spring-security-core: -> 3.2.7.RELEASE
     +--- aopalliance:aopalliance:1.0
     +--- org.springframework:spring-beans:3.2.13.RELEASE -> 4.1.7.RELEASE (*)
     +--- org.springframework:spring-expression:3.2.13.RELEASE -> 4.1.7.RELEASE (*)
     +--- org.springframework:spring-aop:3.2.13.RELEASE -> 4.1.7.RELEASE (*)
     +--- org.springframework:spring-context:3.2.13.RELEASE -> 4.1.7.RELEASE
     |    +--- org.springframework:spring-aop:4.1.7.RELEASE (*)
     |    +--- org.springframework:spring-beans:4.1.7.RELEASE (*)
     |    +--- org.springframework:spring-core:4.1.7.RELEASE (*)
     |    \--- org.springframework:spring-expression:4.1.7.RELEASE (*)
     \--- org.springframework:spring-core:3.2.13.RELEASE -> 4.1.7.RELEASE (*)

是否可以在不先从 org.springframework.security:spring-security-core 中排除 org.springframework:spring-context 的情况下排除 org.springframework:spring-expression

为了从任何配置中排除依赖项,请使用:

 configurations {
   all {
     exclude group: 'org.springframework', module: 'spring-expression'
   }
 }

如果要强制执行特定版本的依赖项,您可以使用:

 configurations.all {
   resolutionStrategy.eachDependency { DependencyResolveDetails details ->
     if (details.requested.group == 'org.springframework') {
       details.useVersion '3.2.13.RELEASE'
     }
   }
 }

如果使用不同版本多次拉取传递依赖项,这可能会有所帮助。

我建议将此添加到您的 Gradle 构建中,也许:

dependencies {
  // Explicitly include spring-expression transitive dependency then manage its dependencies
  compile('org.springframework:spring-context:3.2.13.RELEASE') {
    transitive = false
  }
}

您还可以强制Gradle用户指南

的特定传递依赖项See Section 52.4.2. Client module dependencies