Gradle技术问询:能否更简洁地为两个配置分配同一依赖?
优化Gradle重复依赖的几种简洁方案
当然有更简洁的方式来避免重复配置相同依赖!Gradle提供了几种优雅的方案,帮你把重复代码收拢,让build脚本更干净易维护。下面是几个常用的方法:
1. 定义共享依赖变量
最简单直接的方式就是把重复的依赖放进一个变量里,然后在需要的配置中引用这个变量。不管是Groovy DSL还是Kotlin DSL都支持这种方式:
Groovy DSL 示例
// 先定义共享的依赖集合 def commonSqlDependencies = [ 'com.example:db-library:1.0.0', 'org.slf4j:slf4j-api:2.0.7' ] dependencies { // 直接在两个配置中引用变量 sql commonSqlDependencies anotherTargetConfig commonSqlDependencies }
Kotlin DSL 示例
val commonSqlDependencies = listOf( "com.example:db-library:1.0.0", "org.slf4j:slf4j-api:2.0.7" ) dependencies { sql(commonSqlDependencies) anotherTargetConfig(commonSqlDependencies) }
这种方式适合依赖集合比较固定、不需要额外配置属性的场景,代码改动最小,一目了然。
2. 利用配置继承
如果除了依赖之外,你还希望两个配置共享一些其他的配置规则(比如依赖解析策略、排除规则等),那么配置继承会是更好的选择:
Groovy DSL 示例
configurations { // 创建一个基础配置,用来存放共享依赖和规则 commonSql { // 可以在这里添加共享的配置规则,比如排除某个传递依赖 exclude group: 'commons-logging', module: 'commons-logging' } // 让目标配置继承基础配置 sql.extendsFrom(commonSql) anotherTargetConfig.extendsFrom(commonSql) } dependencies { // 只需要在基础配置中添加一次依赖 commonSql 'com.example:db-library:1.0.0' commonSql 'org.slf4j:slf4j-api:2.0.7' }
Kotlin DSL 示例
configurations { val commonSql by creating { exclude(group = "commons-logging", module = "commons-logging") } val sql by getting { extendsFrom(commonSql) } val anotherTargetConfig by getting { extendsFrom(commonSql) } } dependencies { commonSql("com.example:db-library:1.0.0") commonSql("org.slf4j:slf4j-api:2.0.7") }
这样一来,sql和anotherTargetConfig不仅会继承commonSql的所有依赖,还会继承你在commonSql里设置的所有配置规则,扩展性更强。
3. 使用Gradle的依赖平台(进阶)
如果你的项目是多模块结构,或者需要在多个地方共享一组版本对齐的依赖,可以考虑用Gradle的依赖平台(Dependency Platform),不过这个方案更适合复杂场景,如果你只是单模块里的两个配置重复,前面两种方法已经足够好用了。
内容的提问来源于stack exchange,提问作者Ed Dunn
相关产品推荐
相关产品推荐

