Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

2.4. Gradle 5

2.4.1. 安裝 Gradle

2.4.1.1. CentOS

安裝 Gradle

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

安裝後運行 gradle --help 驗證釋放正確安裝。

			
neo@MacBook-Pro ~ % gradle --help

Welcome to Gradle 5.1.1!

Here are the highlights of this release:
 - Control which dependencies can be retrieved from which repositories
 - Production-ready configuration avoidance APIs

For more details see https://docs.gradle.org/5.1.1/release-notes.html


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

-?, -h, --help            Shows this help message.
-a, --no-rebuild          Do not rebuild project dependencies.
-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.
-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.
-m, --dry-run             Run the builds with all task actions disabled.
--max-workers             Configure the number of concurrent workers Gradle is allowed to use.
--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.
--no-scan                 Disables the creation of a build scan. For more information about build scans, please visit https://gradle.com/build-scans.
--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.
--priority                Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Values are 'normal' (default) or 'low' [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.
--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)
--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.
--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.
			
			

2.4.1.2. Mac

			
neo@MacBook-Pro ~ %  brew install gradle
			
			

2.4.2. 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!!!
			
		

2.4.3. gradle 命令

2.4.3.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.4. build.gradle

apply plugin

		
apply plugin: 'java'		
		
		

2.4.4.1. repositories

			
repositories {
    mavenCentral()
}			
			
			

配置阿里雲倉庫

			
allprojects {
    repositories {
        maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
    }
}			
			
			

2.4.4.2. dependencies

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

2.4.4.3. jar

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

設置 Main-Class

			
jar {
    manifest {
        attributes 'Main-Class': 'demo.Test'
        attributes 'Class-Path': 'junit5.jar'
    }
}			
			
			

2.4.5. gradle.properties

2.4.5.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.5.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.5.3. 

			
ext {
     Name='Neo'
}

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

2.4.5.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