Gradle 总结

Posted by Simon Dong on 2014-09-07

Gradle 是新一代的构建支持系统,集成了Ant和Maven两者的优点,下面是使用中的一些总结:

编译时使用UTF8而不是系统编码

1
[compileJava, javadoc, compileTestJava]*.options*.encoding = 'UTF-8'

引入插件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
apply plugin 'rebel'
buildscript {
repositories {
mavenCentral()
mavenRepo(
name: 'zt-public-snapshots',
url: 'http://repos.zeroturnaround.com/nexus/content/groups/zt-public/'
)
}

dependencies {
classpath group: 'org.zeroturnaround', name: 'gradle-jrebel-plugin', version: '1.1.2'
}
}

依赖来源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
repositories {
mavenLocal()
mavenCentral()
jcenter()

flatDir{
dirs 'extLib'
}

mavenRepositories.each{
name, url ->
maven{
setName(name)
setUrl(url)
}
}
}

在build.gradle中定义属性

1
2
3
ext{
<propName> = ...
}

Example:

1
2
3
4
5
6
7
8
9
ext{
mavenRepositories = [
'jboss' : 'https://repository.jboss.org/nexus/content/groups/public',
'springsource' : 'http://repo.springsource.org/release',
'atlassin' : 'https://maven.atlassian.com/repository/public',
'ibiblio' : 'http://mirrors.ibiblio.org/pub/mirrors/maven2',
'jenkins' : 'http://repo.jenkins-ci.org/releases'
]
}

定义源代码集和输出路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sourceSets{
main{
java{
srcDirs 'src/main','src/config'
}

output.classesDir = 'WebContent/WEB-INF/classes'
}

test{
java{
srcDirs 'src/test'
}

output.classesDir = 'WebContent/WEB-INF/classes'
}
}

依赖的版本处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
ext{
dependenciesVersions = [
'org.springframework' : '3.1.1.RELEASE',
'org.hibernate' : '3.6.10.Final',
'org.slf4j' : '1.7.5',
'org.apache.shiro' : '1.2.2',
'org.apache.httpcomponents' : '4.3',
'org.aspectj' : '1.7.4',
'org.jbpm.jbpm4' : '4.4',
'org.apache.poi' : '3.9',
'org.apache.cxf' : '2.6.8'
]
}

def library(groupId,artifactId){
String.format("%s:%s:%s",groupId,artifactId,dependenciesVersions[groupId])
}

ext{
compileLibs = [

/* logging */
library('org.slf4j','slf4j-log4j12'),

/* shiro */
library('org.apache.shiro','shiro-all'),

/* redis */
'redis.clients:jedis:2.1.0',

/* Spring Framewrok */
library('org.springframework','spring-webmvc'),
library('org.springframework','spring-orm'),
'cglib:cglib-nodep:2.2',
library('org.aspectj','aspectjrt'),
library('org.aspectj','aspectjweaver'),
'com.googlecode.ehcache-spring-annotations:ehcache-spring-annotations:1.2.0'
]
}

dependencies {

compile fileTree(dir: 'extlib', include: '*.jar')




compileLibs.each{
v -> compile(v)
}



testLibs.each{
v -> testCompile(v)
}


}

文件拷贝和文件同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
task copyLibs(type: Copy) {

println 'Copy All Dependencies into Lib'
from configurations.runtime
into 'WebContent/WEB-INF/lib'

}

task site(dependsOn: copyLibs,type: Sync){
println 'generate Site'
from 'WebContent'
into 'site'

}