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 命令

2.4.1.1. tasks 列出任务

			
[neo@netkiller test]$ gradle tasks
: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
-----------
wrapper

Rules
-----
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>

BUILD SUCCESSFUL

Total time: 5.157 secs
			
			

2.4.2. build.gradle

apply plugin

apply plugin: 'java'
		

2.4.2.1. repositories

repositories {
    mavenCentral()
}
			

2.4.2.2. dependencies

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

2.4.2.3. jar

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

2.4.3. gradle.properties

2.4.3.1. 列出 properties

[neo@netkiller gradle]$ gradle properties
: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'
group: 
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@172.16.0.1:example.com/admin.example.com.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

BUILD SUCCESSFUL

Total time: 4.672 secs
			

2.4.3.2. 自定义 gradle.properties

[neo@netkiller gradle]$ cat gradle.properties 
Name=Netkiller
Email=netkiller@msn.com
			
[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']
}				
			
			

2.4.3.3. 

			
ext {
     Name='Neo'
}

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

2.4.3.4. System.properties

-D 参数传递

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

$ gradle hello -DName='Neo' -q
Neo
			
			

-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) {
    System.out.println("Helloworld!!!");
  }
}
		
		
$ gradle build
$ gradle run -q
Helloworld!!!
	




原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。

目录
相关文章
|
存储 缓存 Java
Gradle下载&安装 Gradle wrapper(gradlew)
Gradle的仓库可以和Maven的仓库为同一个,环境变量中的名字必须为 GRADLE_USER_HOME,相当于配置Gradle 本地仓库位置和 Gradle Wrapper 缓存目录
443 0
|
5月前
|
Java API Maven
Gradle使用总结
Gradle使用总结
118 0
|
9月前
|
缓存 Java Maven
gradle
Gradle 是一个现代化的构建工具,它可以帮助开发人员管理项目依赖、构建项目、运行测试、打包和部署项目等。与 Maven 类似,Gradle 也是一种基于约定的构建系统,它不仅可以管理 Java 项目,还可以管理 Android 应用程序、Kotlin 项目、Groovy 项目等。
999 1
|
前端开发 Java Maven
Gradle build.gradle 文件
Gradle build.gradle 文件
Gradle build.gradle 文件
Gradle Avoiding traps
Groovy script variables 4. Groovy 脚本变量 对于 Groovy DSL 的用户来说,了解 Groovy 如何处理脚本变量非常重要。 有两种类型的脚本变量。 一个具有本地作用域,另一个具有脚本范围。 Example: Variables scope: local and script wide 示例: 变量范围: 本地范围和脚本范围 scope.groovy String localScope1 = 'localScope1' def localScope2 = 'localScope2' scriptScope = 'scriptScope' println
100 0
|
Java Android开发
gradle配置 flavor和buildType小结
gradle配置 flavor和buildType小结
5756 0
|
Java Apache Kotlin
Gradle系列01 Gradle介绍与安装
说明 Gradle官网 版本:gradle-5.6.4 系统:macOS Gradle简介 Gradle是一个基于Apache Ant和Apache Maven概念的项目自动化构建开源工具。它使用一种基于Groovy的特定领域语言(DSL)来声明项目设置,目前也增加了基于Kotlin语言的kotlin-based DSL,抛弃了基于XML的各种繁琐配置。
|
API Android开发 数据安全/隐私保护
Gradle 使用技巧(一)
前言 Gradle是使用Groovy语言构建,所以既然是语言,那么就有他的语法,而不是简单的配置项。关于Gradle有时间会出一系列的文章。 1. 自定义apk输出名称 (3.0) 本配置为Android studio3.0及以上的配置,3.0以下版本适用,下面的配置会将所有的Variants都输出。
1166 0