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

如何修改Gradle自定义配置的默认依赖文件扩展名?

如何让Gradle自定义配置默认使用指定扩展名

当然可以搞定这个问题!你完全不需要让用户每次都手动声明ext:'custom',只需要在插件里对custom配置做一些针对性的设置,就能让Gradle自动以.custom作为该配置依赖的默认扩展名。下面给你两种可行的方案:

方案一:基于Gradle属性系统的规范实现(推荐)

这种方式符合Gradle的依赖解析设计理念,通过明确配置的属性来指定它期望的依赖类型:

  1. 创建配置并定义属性
    在你的插件代码中,创建custom配置时,为它添加属性,标记它对应的库元素类型为custom:
import org.gradle.api.attributes.Category
import org.gradle.api.attributes.LibraryElements
import org.gradle.api.attributes.Usage

def customConfig = project.configurations.create("custom") {
    // 配置该依赖的用途、类别和元素类型
    attributes {
        attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage, "custom-dependency"))
        attribute(Category.CATEGORY_ATTRIBUTE, project.objects.named(Category, Category.LIBRARY))
        attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements, "custom"))
    }
    // 确保配置可以被解析(用于拉取外部依赖)
    canBeResolved = true
}
  1. 映射Artifact类型到扩展名
    告诉Gradle,custom类型的库元素对应的文件扩展名就是custom:
project.dependencies.artifactTypes.named("custom") {
    extension = "custom"
}

方案二:自动补全依赖的扩展名(简便快捷)

如果你觉得属性配置有点繁琐,也可以通过监听依赖添加事件,自动为custom配置的依赖补上默认扩展名:

project.dependencies.whenObjectAdded { dep ->
    // 只处理外部模块依赖、目标配置是custom且未指定扩展名的情况
    if (dep instanceof org.gradle.api.artifacts.ExternalModuleDependency && 
        dep.targetConfiguration == "custom" && 
        dep.ext == null) {
        dep.ext = "custom"
    }
}

效果验证

现在用户只需要像平常一样声明依赖:

dependencies {
    custom group: 'my-custom', name: 'my-custom', version: '1.0.00'
}

Gradle就会自动去查找my-custom-1.0.00.custom文件,而不是默认的.jar。如果用户需要使用其他扩展名的依赖,依然可以手动指定ext参数来覆盖默认值,比如:

dependencies {
    custom group: 'my-custom', name: 'my-custom', version: '1.0.00', ext: 'other'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:36:38