Java構建工具三強: Ant, Maven, Gradle
Ant歷史悠久, 用build.xml 描述, 當時他的xml着實讓不少工程師頭痛, 但仍有用武之地.
Maven 用pom.xml 文件描述, 是對ant的補充, 項目統一管理的得力助手, 統一的依賴包使得項目再也不爲版本不一致而發愁.
Gradle 用build.gradle文件, 可讀性更強, 使用更方便, 可謂如日中天.html
來自百科解讀:
Gradle是一個基於Apache Ant和Apache Maven概念項目自動化構建開源工具。它使用基於Groovy的特定領域語言(DSL)來聲明項目設置,拋棄了基於XML的各類繁瑣配置。
面向Java應用爲主, 當前支持的語言限於Java、Groovy、Kotlin和Scala,計劃將來將支持更多的語言。java
功能正則表達式
安裝以前須要什麼?數據庫
本文推薦java 1.8 +Gradle 5.4tomcat
Windows用戶下載安裝包:https://gradle.org/next-steps/?version=5.4.1&format=binbash
Mac os 或者 Linux 用戶更爲簡單
$ brew install gradle
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/cask and homebrew/core).
==> Updated Formulae
sphinx-doc ✔ grakn jenkins-lts tomcat微信
==> Downloading https://services.gradle.org/distributions/gradle-5.4.1-all.zip
==> Downloading from https://downloads.gradle.org/distributions/gradle-5.4.1-all.zip
######################################################################## 100.0%
🍺 /usr/local/Cellar/gradle/5.4.1: 13,767 files, 235.5MB, built in 2 minutes 13 secondsapp
$ gradle -v框架
Welcome to Gradle 5.4.1!maven
Here are the highlights of this release:
- Run builds with JDK12
- New API for Incremental Tasks
- Updates to native projects, including Swift 5 support
For more details see https://docs.gradle.org/5.4.1/release-notes.html
------------------------------------------------------------
Gradle 5.4.1
------------------------------------------------------------
Build time: 2019-04-26 08:14:42 UTC
Revision: 261d171646b36a6a28d5a19a69676cd098a4c19d
Kotlin: 1.3.21
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 1.8.0_161 (Oracle Corporation 25.161-b12)
OS: Mac OS X 10.13.6 x86_64
安裝信息告訴咱們gradle安裝路徑是: /usr/local/Cellar/gradle/5.4.1
設置環境變量: (推薦)
以mac 爲例
$ vi ~/.bash_profile 增長以下內容
$ export PATH=$PATH:/opt/gradle/gradle-5.4.1/bin
$ source ~/.bash_profile
Windows 用戶:
path中增長 C:\Gradle\gradle-5.4.1\bin 具體根據你安裝的目錄配置
驗證安裝初始化:
louiezhou$ gradle -v
------------------------------------------------------------
Gradle 5.4.1
------------------------------------------------------------
Build time: 2019-04-26 08:14:42 UTC
Revision: 261d171646b36a6a28d5a19a69676cd098a4c19d
Kotlin: 1.3.21
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 1.8.0_161 (Oracle Corporation 25.161-b12)
OS: Mac OS X 10.13.6 x86_64
查看使用方法:
louiezhou$ gradle -h
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.
1 export PATH=/opt/local/bin:/opt/local/sbin:$PATH
--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.
一. 建立java application:
louiezhou$ mkdir demo #建立一個目錄
louiezhou$ cd demo/
louiezhou$ ls
louiezhou$ gradle init #初始化建立項目
Select type of project to generate:
1: basic
2: cpp-application
3: cpp-library
4: groovy-application
5: groovy-library
6: java-application
7: java-library
8: kotlin-application
9: kotlin-library
10: scala-library
Enter selection (default: basic) [1..10] 6
Select build script DSL:
1: groovy
2: kotlin
Enter selection (default: groovy) [1..2] 1
Select test framework:
1: junit
2: testng
3: spock
Enter selection (default: junit) [1..3] 2
Project name (default: demo):
Source package (default: demo):
BUILD SUCCESSFUL in 22s
2 actionable tasks: 2 executed
初始化生成目錄:
build.gradle gradle gradlew gradlew.bat settings.gradle src
初始化結束後, 選擇一個我的喜愛的編輯器, 我的比較這喜歡Atom or Sublime 輕巧方便, 不像Eclipse那樣龐大笨重.
打開Atom 導入工程便可瀏覽目錄.
├── build.gradle
├── gradle #wrapper的文件
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
│ └── java #源代碼
│ └── App.java
└── test #測試代碼
└── java
└── AppTest.java
---------------------
App.java
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package demo;
public class App {
public String getGreeting() {
return "Hello world, this is a first gradle application + 中文測試!";
}
public static void main(String[] args) {
System.out.println(new App().getGreeting());
}
}
AppTest.java
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package demo;
import org.testng.annotations.*;
import static org.testng.Assert.*;
public class AppTest {
@Test public void appHasAGreeting() {
App classUnderTest = new App();
assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");
}
}
settings.gradle
rootProject.name = 'demo'
配置build.gradle
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* User Manual available at https://docs.gradle.org/5.4.1/userguide/tutorial_java_projects.html
*/
plugins {
// Apply the java plugin to add support for Java
id 'java' #java插件
// Apply the application plugin to add support for building an application
id 'application'
}
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter() #公有倉庫
}
/****編譯編碼,解決Gradle編譯時出現: 編碼GBK的不可映射字符****/
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
dependencies { #添加依賴
// This dependency is found on compile classpath of this component and consumers.
implementation 'com.google.guava:guava:27.0.1-jre' #依賴google的guava
// Use TestNG framework, also requires calling test.useTestNG() below
testImplementation 'org.testng:testng:6.14.3' #依賴testNG測試庫
}
// Define the main class for the application
mainClassName = 'demo.App' #main 類
test {
// Use TestNG for unit tests
useTestNG() #testNT 單元測試
}
二. 執行構建
louie-mac:demo louiezhou$ ./gradlew build
BUILD SUCCESSFUL in 25s
7 actionable tasks: 7 executed
louie-mac:demo louiezhou$ ls
build build.gradle gradle gradlew gradlew.bat settings.gradle src
當咱們執行完build命令後, 會在項目目錄中生成class文件 目錄:build->classes->java->main->demo->App.class
三. 由於Gradle構建使用了Application plugin,使用tasks任務來查看插件添加的那些任務
louie-mac:demo louiezhou$ ./gradlew tasks
> Task :tasks
------------------------------------------------------------
Tasks runnable from root project
------------------------------------------------------------
Application tasks
-----------------
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.
wrapper - Generates Gradle wrapper files.
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
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'demo'.
components - Displays the components produced by root project 'demo'. [incubating]
dependencies - Displays all dependencies declared in root project 'demo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'demo'.
dependentComponents - Displays the dependent components of components in root project 'demo'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'demo'. [incubating]
projects - Displays the sub-projects of root project 'demo'.
properties - Displays the properties of root project 'demo'.
tasks - Displays the tasks runnable from root project 'demo'.
Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.
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 gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed
四. 最後就是run
louie-mac:demo louiezhou$ ./gradlew run
> Task :run
Hello world, this is a first gradle application + 中文測試! #App 的main 輸出咱們設定的內容
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
參考文獻: https://gradle.org/install/
尚書·大禹謨---人心唯危,道心唯微,唯精唯一,允執厥中, 天之歷數在爾躬,允執其中.
今日精選推薦
諮詢工做加微信
掃描二維碼
歡迎自薦和推薦, 須要的微信推送簡歷!
請猛戳下面二維碼瞭解更多