在Gradle中,我如何在一个地方声明通用的依赖关系? [英] In Gradle, how do I declare common dependencies in a single place?

查看:212
本文介绍了在Gradle中,我如何在一个地方声明通用的依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Maven中,当你可以在父POM的< dependencyManagement> 部分中定义一个依赖项时,会有一个非常有用的特性,并且不需要从子模块引用该依赖项指定版本或作用域或其他。



Gradle中有哪些选择?

解决方案

您可以在父脚本中声明常见的依赖关系:



ext.libraries = [// Groovy映射文字
spring_core:org.springframework:spring-core:3.1,
junit:junit:junit:4.10
]

在子脚本中,可以使用如下的依赖声明:

dependencies {
compile libraries.spring_core
testCompile libraries.junit
}

使用高级配置共享依赖声明你可以使用 DependencyHandler.create
$ b

spring_core:dependencies.create(org.springframework:spring-core:3.1){
排除模块:commons-logging
force = true






多个依赖关系可以在同一个名称下共享:

libraries = [
spring:[// Groovy list literal
org .springframework:spring-core:3.1,
org.springframework:spring-jdbc:3.1
]
]

dependencies {compile libraries.spring} 会立即添加两个依赖项。



无法以这种方式共享的信息是应该分配依赖关系的配置(Maven术语中的 scope )。不过,从我的经验来看,最好还是要明确这一点。


In Maven there is a very useful feature when you can define a dependency in the <dependencyManagement> section of the parent POM, and reference that dependency from child modules without specifying the version or scope or whatever.

What are the alternatives in Gradle?

解决方案

You can declare common dependencies in a parent script:

ext.libraries = [ // Groovy map literal
    spring_core: "org.springframework:spring-core:3.1",
    junit: "junit:junit:4.10"
]

From a child script, you can then use the dependency declarations like so:

dependencies {
    compile libraries.spring_core
    testCompile libraries.junit
}

To share dependency declarations with advanced configuration options, you can use DependencyHandler.create:

libraries = [
    spring_core: dependencies.create("org.springframework:spring-core:3.1") {
        exclude module: "commons-logging"
        force = true
    }
]

Multiple dependencies can be shared under the same name:

libraries = [
    spring: [ // Groovy list literal
        "org.springframework:spring-core:3.1", 
        "org.springframework:spring-jdbc:3.1"
    ]
]

dependencies { compile libraries.spring } will then add both dependencies at once.

The one piece of information that you cannot share in this fashion is what configuration (scope in Maven terms) a dependency should be assigned to. However, from my experience it is better to be explicit about this anyway.

这篇关于在Gradle中,我如何在一个地方声明通用的依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆