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

如何通过单一配置为两种构建类型添加依赖?

实现Gradle多构建类型/风味的依赖批量配置

你的项目配置如下:

productFlavors {
    free
    paid
}

buildTypes {
    debug
    beta
    release
}

要实现一次性给多个构建类型(比如debug和beta)添加相同依赖,不用重复编写多条依赖声明,有两种实用方法:

方法1:利用配置继承

通过自定义一个组合配置,让它继承目标构建类型的配置,这样给组合配置添加的依赖会自动同步到对应的构建类型中:

configurations {
    // 让debugBetaImplementation继承debug和beta的实现配置
    debugBetaImplementation.extendsFrom debugImplementation, betaImplementation
}

dependencies {
    debugBetaImplementation "some-dependency"
}

这段代码的效果完全等效于分别给debugImplementation和betaImplementation添加依赖。

方法2:循环批量添加依赖

如果需要批量处理多个构建类型或风味,可以用Groovy的循环动态生成依赖声明,灵活性更高:

// 定义需要添加依赖的目标构建类型列表
def targetBuildTypes = ['debug', 'beta']

targetBuildTypes.each { buildType ->
    dependencies {
        "${buildType}Implementation" "some-dependency"
    }
}

如果是要组合多个风味,比如给free和paid同时加依赖,只需要把列表换成风味名称,配置后缀换成Implementation即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:35:29