实践Gradle

介绍

Gradle是一个构建工具,类似ant/maven

安装

需要jdk/jre7.0或以上版本

可以参考官方安装说明

二进制发行包

到官方下载二进制发行包,解压缩,设定环境变量即可。

通过包管理器

*nix系统可以使用SDKMAN,Mac可以使用Homebrew,Windows可以使用Scoop

1
$ sdk install gradle 4.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ gradle -v

------------------------------------------------------------
Gradle 4.0
------------------------------------------------------------

Build time:   2017-06-14 15:11:08 UTC
Revision:     316546a5fcb4e2dfe1d6aa0b73a4e09e8cecb5a5

Groovy:       2.4.11
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_101 (Oracle Corporation 25.101-b13)
OS:           Linux 4.9.0-deepin6-amd64 amd64

命令

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
$ gradle -h
Picked up _JAVA_OPTIONS:   -Dawt.useSystemAAFontSettings=gasp

USAGE: gradle [option...] [task...]

-?, -h, --help            Shows this help message.
-a, --no-rebuild          Do not rebuild project dependencies. [deprecated]
-b, --build-file          Specify the build file.
--build-cache             Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.
-c, --settings-file       Specify the settings file.
--configure-on-demand     Configure necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds. [incubating]
--console                 Specifies which type of console output to generate. Values are 'plain', 'auto' (default), 'rich' or 'verbose'.
--continue                Continue task execution after a task failure.
-D, --system-prop         Set system property of the JVM (e.g. -Dmyprop=myvalue).
-d, --debug               Log in debug mode (includes normal stacktrace).
--daemon                  Uses the Gradle Daemon to run the build. Starts the Daemon if not running.
--foreground              Starts the Gradle Daemon in the foreground. [incubating]
-g, --gradle-user-home    Specifies the gradle user home directory.
-I, --init-script         Specify an initialization script.
-i, --info                Set log level to info.
--include-build           Include the specified build in the composite. [incubating]
-m, --dry-run             Run the builds with all task actions disabled.
--max-workers             Configure the number of concurrent workers Gradle is allowed to use. [incubating]
--no-build-cache          Disables the Gradle build cache.
--no-configure-on-demand  Disables the use of configuration on demand. [incubating]
--no-daemon               Do not use the Gradle daemon to run the build. Useful occasionally if you have configured Gradle to always run with the daemon by default.
--no-parallel             Disables parallel execution to build projects. [incubating]
--no-scan                 Disables the creation of a build scan. For more information about build scans, please visit https://gradle.com/build-scans. [incubating]
--offline                 Execute the build without accessing network resources.
-P, --project-prop        Set project property for the build script (e.g. -Pmyprop=myvalue).
-p, --project-dir         Specifies the start directory for Gradle. Defaults to current directory.
--parallel                Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use. [incubating]
--profile                 Profile build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir       Specify the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet               Log errors only.
--recompile-scripts       Force build script recompiling. [deprecated]
--refresh-dependencies    Refresh the state of dependencies.
--rerun-tasks             Ignore previously cached task results.
-S, --full-stacktrace     Print out the full (very verbose) stacktrace for all exceptions.
-s, --stacktrace          Print out the stacktrace for all exceptions.
--scan                    Creates a build scan. Gradle will emit a warning if the build scan plugin has not been applied. (https://gradle.com/build-scans) [incubating]
--status                  Shows status of running and recently stopped Gradle Daemon(s).
--stop                    Stops the Gradle Daemon if it is running.
-t, --continuous          Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change. [incubating]
-u, --no-search-upward    Don't search in parent folders for a settings file.
--update-locks            Perform a partial update of the dependency lock, letting passed in module notations change version. [incubating]
-v, --version             Print version info.
-w, --warn                Set log level to warn.
--warning-mode            Specifies which mode of warnings to generate. Values are 'all', 'summary'(default) or 'none'
--write-locks             Persists dependency resolution for locked configurations, ignoring existing locking information if it exists [incubating]
-x, --exclude-task        Specify a task to be excluded from execution.

build.gradle

1
2
3
4
5
jar {
	group 'wang.ray.gradle'
    baseName = 'sample-gradle'
    version =  '0.1.0'
}

插件(Plugins)

1
apply plugin: 'java'

任务(Tasks)

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
## 查看可执行的task
$ gradle tasks

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'ray'.
components - Displays the components produced by root project 'ray'. [incubating]
dependencies - Displays all dependencies declared in root project 'ray'.
dependencyInsight - Displays the insight into a specific dependency in root project 'ray'.
dependentComponents - Displays the dependent components of components in root project 'ray'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'ray'. [incubating]
projects - Displays the sub-projects of root project 'ray'.
properties - Displays the properties of root project 'ray'.
tasks - Displays the tasks runnable from root project 'ray'.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
1
2
3
4
# 构件
$ gradle build
# 跳过单元测试
$ gradle build -x test

help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ gradle help

> Task :help

Welcome to Gradle 4.10.2.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

For troubleshooting, visit https://help.gradle.org

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
1
$ gradle help --task tasks

依赖

1
2
3
dependencies {
    compile "joda-time:joda-time:2.2"
}

强制刷新依赖

1
$ gradle --refresh-dependencies assemble

仓库

1
2
3
4
5
repositories {
    mavenLocal()
    mavenCentral()
    maven { url "http://m2.neo4j.org/content/repositories/releases" }
}

可以通过定义环境变量设定gradle用户home目录(默认值为:~/.gradle

1
export GRADLE_USER_HOME=/media/ray/Resource/GradleUserHome

gradle本地仓库在gradle用户home目录下,默认路径:${home}/.gradle/caches/modules-2/files-2.1/

setting.gradle

子模块

1
include 'module1','module2'

初始化函数

Gradle Wrapper

Gradle Wrapper的作用是将gradle的版本纳入项目管理中,实现gradle的版本由项目控制,与运行环境无关,也不需要当前环境安装有gradle,首次运行时自动下载相应版本的gradle到当前环境,升级也会非常容易。不会使用当前环境已安装的gradle。

安装

1
2
3
4
5
6
# 通过wrapper任务初始化gradle wrapper
$ gradle wrapper
# 指定gradle版本
$ gradle wrapper --gradle-version 4.0
# --distribution-type: bin/all
# --gradle-distribution-url: 指定gradle源文件路径

下载的gradle放到gradle用户home目录下的wrapper/dist目录

默认使用当前环境的gradle版本作为gradle wrapper的gradle版本,也可以通过如下配置定制wrapper任务,比如指定gradle版本

1
2
3
4
# build.gradle中新增如下配置,指定初始化时gradle的版本
task wrapper(type: Wrapper) {
    gradleVersion = '4.0'
}
1
2
3
4
5
6
7
8
# 项目根目录生成如下gradle wrapper相关文件,将这些文件添加到版本管理。
└── sample-gradle
    └── gradlew
    └── gradlew.bat
    └── gradle
        └── wrapper
            └── gradle-wrapper.jar
            └── gradle-wrapper.properties

实际gradle wrapper使用过程中,与wrapper配置没有关系,是生成的这些文件起作用。

gradle-wrapper.properties文件可以进行一些配置,例如:

1
2
3
4
5
6
#Wed Aug 09 10:42:27 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-bin.zip

使用

1
2
# 使用gradlew命令代替原始的gradle
$ ./gradlew -v

首次会自动下载相应版本的gradle

升级

方法一:

修改build.properties中初始化gradle版本,重新安装

方法二:

1
2
# 升级gradle wrapper使用的gradle版本
$ ./gradlew wrapper --gradle-version=4.1 --distribution-type=bin

这种升级方法会导致build.properties中指定的初始化版本【如果有】与实际使用的gradle版本不一致。