Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

2.4. Gradle

安装 Gradle

curl -s https://raw.githubusercontent.com/oscm/shell/38c2d4d307ce7a0760fc88d5d9703eef64d3b81c/lang/java/gradle/gradle-2.9.sh | bash	

安装后运行 gradle --help 验证释放正确安装。

# gradle --help

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

-?, -h, --help          Shows this help message.
-a, --no-rebuild        Do not rebuild project dependencies.
-b, --build-file        Specifies the build file.
-c, --settings-file     Specifies the settings file.
--configure-on-demand   Only relevant projects are configured in this build run. This means faster build for large multi-project builds. [incubating]
--console               Specifies which type of console output to generate. Values are 'plain', 'auto' (default) or 'rich'.
--continue              Continues 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.
--gui                   Launches the Gradle GUI.
-I, --init-script       Specifies an initialization script.
-i, --info              Set log level to info.
-m, --dry-run           Runs the builds with all task actions disabled.
--max-workers           Configure the number of concurrent workers Gradle is allowed to use. [incubating]
--no-color              Do not use color in the console output. [deprecated - use --console=plain instead]
--no-daemon             Do not use the Gradle daemon to run the build.
--offline               The build should operate 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]
--parallel-threads      Build projects in parallel, using the specified number of executor threads. [deprecated - Please use --parallel, optionally in conjunction with --max-workers.] [incubating]
--profile               Profiles build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir     Specifies the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet             Log errors only.
--recompile-scripts     Force build script recompiling.
--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.
--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.gradle file.
-v, --version           Print version info.
-x, --exclude-task      Specify a task to be excluded from execution.	

2.4.1. gradle 命令 tasks 列出任务

[neo@netkiller test]$ gradle tasks

All tasks runnable from root project

Application tasks
installApp - Installs the project as a JVM application along with libs and OS specific scripts.
run - Runs this project as a JVM application

Build tasks
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
init - Initializes a new Gradle build. [incubating]

Distribution tasks
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.

Documentation tasks
javadoc - Generates Javadoc API documentation for the main source code.

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

Verification tasks
check - Runs all checks.
test - Runs the unit tests.

Other tasks

Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.

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

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


Total time: 5.157 secs

2.4.2. build.gradle

apply plugin

apply plugin: 'java' repositories

repositories {
} dependencies

dependencies {
    compile 'org.springframework:spring-context:4.2.2.RELEASE'
} jar

jar {
    baseName = 'hello'
    version =  '0.1.0'

2.4.3. gradle.properties 列出 properties

[neo@netkiller gradle]$ gradle properties

Root project

allprojects: [root project 'gradle']
ant: org.gradle.api.internal.project.DefaultAntBuilder@12072edc
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@159576c3
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@7a80747
asDynamicObject: org.gradle.api.internal.ExtensibleDynamicObject@2875ca3e
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@4d30c132
buildDir: /opt/www/gradle/build
buildFile: /opt/www/gradle/build.gradle
buildScriptSource: org.gradle.groovy.scripts.UriScriptSource@3bdbe135
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@609e7d46
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@4532b038
clone: task ':clone'
compile: task ':compile'
compileTest: task ':compileTest'
components: []
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@2cf5006
configurations: []
convention: org.gradle.api.internal.plugins.DefaultConvention@788ebb5a
defaultTasks: []
deferredProjectConfiguration: org.gradle.api.internal.project.DeferredProjectConfiguration@62ae4f8b
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@21e8614a
depth: 0
description: null
dist: task ':dist'
ext: org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@1f4b52aa
extensions: org.gradle.api.internal.plugins.DefaultConvention@788ebb5a
fileOperations: org.gradle.api.internal.file.DefaultFileOperations@a2026f3
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@44dd20b6
gradle: build 'gradle'
inheritedScope: org.gradle.api.internal.ExtensibleDynamicObject$InheritedDynamicObject@118eb00c
logger: org.gradle.logging.internal.slf4j.OutputEventListenerBackedLogger@2ec7ecd5
logging: org.gradle.logging.internal.DefaultLoggingManager@478dabf1
modelRegistry: org.gradle.model.internal.registry.DefaultModelRegistry@26137fea
modelSchemaStore: org.gradle.model.internal.manage.schema.extract.DefaultModelSchemaStore@4a32ef2d
module: org.gradle.api.internal.artifacts.ProjectBackedModule@31bca1c3
name: gradle
parent: null
parentIdentifier: null
path: :
pluginManager: org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@55f49969
plugins: [org.gradle.api.plugins.HelpTasksPlugin@4f88f506]
processOperations: org.gradle.api.internal.file.DefaultFileOperations@a2026f3
project: root project 'gradle'
project.dir: repo
project.url: git@
projectDir: /opt/www/gradle
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@19035ff9
projectRegistry: org.gradle.api.internal.project.DefaultProjectRegistry@2c91e143
properties: {...}
pull: task ':pull'
repositories: []
resources: org.gradle.api.internal.resources.DefaultResourceHandler@1d5c0c91
rootDir: /opt/www/gradle
rootProject: root project 'gradle'
scriptHandlerFactory: org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@63d12a6
scriptPluginFactory: org.gradle.configuration.DefaultScriptPluginFactory@1393537d
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$4@2d4e3d95
services: ProjectScopeServices
standardOutputCapture: org.gradle.logging.internal.DefaultLoggingManager@478dabf1
state: project state 'EXECUTED'
status: release
stop: task ':stop'
subprojects: []
tasks: [task ':clone', task ':compile', task ':compileTest', task ':dist', task ':properties', task ':pull', task ':stop', task ':test']
test: task ':test'
version: unspecified


Total time: 4.672 secs 自定义 gradle.properties

[neo@netkiller gradle]$ cat gradle.properties 
[neo@netkiller gradle]$ gradle properties | egrep "Name|Email"
Email: netkiller@msn.com
Name: Netkiller
[neo@netkiller gradle]$ cat build.gradle 
task hello << {
     println "hello, $Name<$Email>"
[neo@netkiller gradle]$ gradle hello -q
hello, Netkiller<netkiller@msn.com>

通过 systemProp 前缀传递 System.properties 参数

[neo@netkiller gradle]$ cat gradle.properties 
systemProp.Name = 'Neo Chen'

[neo@netkiller gradle]$ cat build.gradle

task hello << {
      println "hello, " + System.properties['Name']

ext {

task hello << {
     println "hello, $Name"
}				 System.properties

-D 参数传递

task hello << {
     println System.properties['Name']

$ gradle hello -DName='Neo' -q

-P 参数传递

task hello << {
      println "hello, $Name"

$ gradle hello -PName='Neo' -q
hello, Neo				

2.4.4. Example

mkdir -p src/main/java/hello

vim src/main/java/hello/HelloWorld.java

package hello;

public class HelloWorld {
  public static void main(String[] args) {
$ gradle build
$ gradle run -q
comments powered by Disqus