You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gradle BOM(java-platform)项目中排除传递依赖?

在Gradle java-platform项目中为BOM添加依赖排除的方法

你遇到的问题核心是:constraints块中的依赖约束(dependency constraint)不支持配置exclude,它仅用于版本强制,不会生成包含排除规则的完整<dependency>条目。要在BOM中生成带<exclusions>的依赖管理配置,需要调整配置方式:

正确配置方式

将需要添加排除规则的依赖从constraints块移至dependencies块的api声明中,同时保留javaPlatform.allowDependencies()启用(允许平台包含完整依赖声明):

plugins {
    id 'java-platform'
}

javaPlatform {
    allowDependencies()
}

dependencies {
    api(platform('org.springframework.boot:spring-boot-dependencies:3.4.3'))

    // 带排除规则的依赖直接声明在dependencies的api中
    api('org.opensearch.client:spring-data-opensearch-starter:1.6.1') {
        exclude group: 'org.opensearch.client', module: 'opensearch-rest-high-level-client'
        exclude group: 'org.apache.httpcomponents'
    }

    // 其他仅需版本约束的依赖仍放在constraints块中
    constraints {
        // 示例:约束其他依赖版本
        // api('com.example:some-lib:1.0.0')
    }
}

原理说明

  • constraints块生成的是<dependencyConstraint>,仅负责版本约束,不支持排除规则;
  • dependencies块中通过api声明的依赖,在allowDependencies()启用时,会被写入BOM的<dependencyManagement>,成为完整的<dependency>条目,其中的exclude配置会自动转换为<exclusions>节点;
  • 这种方式生成的BOM完全符合你期望的XML结构,包含目标依赖的版本和排除规则。

验证结果

执行./gradlew publishToMavenLocal(或publish)后,查看生成的POM文件,会看到如下结构:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.opensearch.client</groupId>
      <artifactId>spring-data-opensearch-starter</artifactId>
      <version>1.6.1</version>
      <exclusions>
        <exclusion>
          <groupId>org.opensearch.client</groupId>
          <artifactId>opensearch-rest-high-level-client</artifactId>
        </exclusion>
        <exclusion>
          <groupId>org.apache.httpcomponents</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <!-- 其他依赖管理条目 -->
  </dependencies>
</dependencyManagement>

内容的提问来源于stack exchange,提问作者pstet17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:25:14