gradle学习笔记

引用

configurations

configurations 是依赖的集合。比如compile configuration对应的是声明的compile dependency集合引用。

1
2
3
4
5
6
7
configurations {
compile
runtime
testCompile.extendsFrom('compile')
testRuntime.extendsFrom('runtime', 'testCompile')
default.extendsFrom('runtime')
}

moudle depenency

moudle就是我们声明的依赖。包括:group, name, and version。声明方式有:

1
2
3
4
5
dependencies {
compile 'org.apache.solr:solr-core:1.4.1'
compile 'org.springframework:spring-core:3.0.5'
testCompile 'junit:junit:4.8'
}
1
2
3
4
5
dependencies {
compile group: 'org.apache.solr', name: 'solr-core' version: '1.4.1'
compile group: 'org.springframework', name: 'spring-core', version: '3.0.5'
testCompile group: 'junit', name: 'junit', version: '4.8'
}
1
2
3
4
5
6
// Fetching Spring Core 3.0.6 without any of its dependencies
dependencies {
compile('org.springframework:spring-core:3.0.6') {
transitive = false
}
}
1
2
3
4
5
6
// Forcing Spring Core 3.0.6 to dominate any other versions of Spring Core in the dependency graph
dependencies {
compile('org.springframework:spring-core:3.0.6.RELEASE') {
force = true
}
}
1
2
3
4
5
6
Avoiding commons-logging as a transitive dependency of Spring Core
dependencies {
compile('org.springframework:spring-core:3.0.6.RELEASE') {
exclude name: 'commons-logging'
}
}

File dependency

1
2
3
4
// Declaring a dependency explicitly on a locally managed module
dependencies {
compile files('lib/hacked-vendor-module.jar')
}
1
2
3
4
// Depending recursively on all of the files under lib
dependencies {
compile fileTree('lib')
}
1
2
3
4
5
// Declaring dependencies on subprojects
dependencies {
compile project(':codec')
compile project(':content')
}

Maven Repositories

In some cases, we might want to obtain POMs from one website (say, a centralized corporate repo), but download build artifacts from a mirrored copy of the repo somewhere else in the network.主要目的是节省带宽,提高下载速度。

1
2
3
4
5
6
7
8
9
10
// Setting the artifact URL as distinct from the default POM URL
repositories {
// Overriding artifacts for an internal repo
maven {
url = 'http://central.megacorp.com/main/repo'
artifactUrls = [ 'http://dept.megacorp.com/local/repo' ]
}
// Obtain Maven Central artifacts locally
mavenCentral artifactUrls: ['http://dept.megacorp.com/maven/central']
}

配置 Resolution Strategy

1
2
3
4
5
6
// Failing the build when a dependency version conflict is detected
configurations.all {
resolutionStrategy {
failOnVersionConflict()
}
}
1
2
3
4
5
6
// Forcing a particular version of a given dependency
configurations.all {
resolutionStrategy {
force 'commons-collections:commons-collections:2.1'
}
}

Changing modules

Changing modules 比如 SNAPSHOT module,gradle默认cahche24小时后更新。

1
2
3
4
5
6
configurations.all {
resolutionStrategy {
cacheDynamicVersionsFor 1, 'hour'
cacheChangingModulesFor 0, 'seconds'
}
}