# 使用Gradle構建Java項目
本指南將引導您逐步使用Gradle構建一個簡單的Java項目。
## 你會建立什么
您將創建一個簡單的應用程序,然后使用Gradle進行構建。
## 你需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 6](https://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續以 [設置項目](https://spring.io/guides/gs/gradle/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-gradle/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-gradle.git](https://github.com/spring-guides/gs-gradle.git)`
* 光盤進入 `gs-gradle/initial`
* 跳到 [安裝Gradle](https://spring.io/guides/gs/gradle/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-gradle/complete`.
## 設置項目
首先,您設置了一個Java項目供Gradle構建。 為了將重點放在Gradle上,現在使該項目盡可能簡單。
### 創建目錄結構
在您選擇的項目目錄中,創建以下子目錄結構; 例如, `mkdir -p src/main/java/hello` 在\* nix系統上:
~~~
└── src
└── main
└── java
└── hello
~~~
內 `src/main/java/hello`目錄中,您可以創建所需的任何Java類。 為了簡單起見并與本指南的其余部分保持一致,Spring建議您創建兩個類: `HelloWorld.java` 和 `Greeter.java`.
`src/main/java/hello/HelloWorld.java`
~~~
package hello;
public class HelloWorld {
public static void main(String[] args) {
Greeter greeter = new Greeter();
System.out.println(greeter.sayHello());
}
}
~~~
`src/main/java/hello/Greeter.java`
~~~
package hello;
public class Greeter {
public String sayHello() {
return "Hello world!";
}
}
~~~
## 安裝Gradle
現在您有了可以使用Gradle生成的項目,您可以安裝Gradle。
強烈建議使用安裝程序:
* [開發人員](https://sdkman.io/)
* [家釀](https://brew.sh) (BREW的gradle安裝)
萬不得已,如果這些工具都不滿足您的需求,則可以從 下載二進制文件 [https://www.gradle.org/downloads](https://www.gradle.org/downloads) 。 僅需要二進制文件,因此請查找gradle- 的鏈接 *version* \-bin.zip 。 (您也可以選擇gradle- *version* \-all.zip來獲取源代碼和文檔以及二進制文件。)
將文件解壓縮到您的計算機,然后將bin文件夾添加到您的路徑。
要測試Gradle的安裝,請從命令行運行Gradle:
~~~
gradle
~~~
如果一切順利,您會看到一條歡迎消息:
~~~
:help
Welcome to Gradle 6.0.1.
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
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 455ms
1 actionable task: 1 executed
~~~
您現在已經安裝了Gradle。
## 找出Gradle可以做什么
現在已經安裝了Gradle,看看它能做什么。 在甚至為項目創建build.gradle文件之前,您都可以詢問它有哪些可用的任務:
~~~
gradle tasks
~~~
您應該看到可用任務的列表。 假設您在尚未具有 夾中運行Gradle *build.gradle* 文件的文件 ,您將看到一些非常基本的任務,例如:
~~~
:tasks
------------------------------------------------------------
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 'gs-gradle'.
components - Displays the components produced by root project 'gs-gradle'. [incubating]
dependencies - Displays all dependencies declared in root project 'gs-gradle'.
dependencyInsight - Displays the insight into a specific dependency in root project 'gs-gradle'.
dependentComponents - Displays the dependent components of components in root project 'gs-gradle'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'gs-gradle'. [incubating]
outgoingVariants - Displays the outgoing variants of root project 'gs-gradle'.
projects - Displays the sub-projects of root project 'gs-gradle'.
properties - Displays the properties of root project 'gs-gradle'.
tasks - Displays the tasks runnable from root project 'gs-gradle'.
To see all tasks and more detail, run gradle tasks --all
To see more detail about a task, run gradle help --task <task>
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.0.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 477ms
1 actionable task: 1 executed
~~~
即使這些任務可用,但如果沒有項目構建配置,它們也不會提供太多價值。 當你充實 `build.gradle`文件,一些任務會更有用。 當您向其中添加插件時,任務列表將增加 `build.gradle`,因此您偶爾會想 運行 **任務** 再次 以查看可用的任務。
說到添加插件,接下來您將添加一個啟用基本Java構建功能的插件。
## 建立Java程式碼
從簡單開始,創建一個非常基礎的 `build.gradle`您在本指南開頭創建的中的文件。 只給它一行:
~~~
apply plugin: 'java'
~~~
構建配置中的這一行帶來了巨大的力量。 運行 **gradle任務** 再次 ,您會看到新任務已添加到列表中,包括用于構建項目,創建JavaDoc和運行測試的任務。
您將 使用 **gradle構建** 經常 任務。 該任務將代碼編譯,測試并將其組裝到一個JAR文件中。 您可以這樣運行它:
~~~
gradle build
~~~
幾秒鐘后,“ BUILD SUCCESSFUL”表明構建已完成。
要查看構建工作的結果,請查看 *構建* 文件夾。 在其中,您將找到幾個目錄,包括以下三個著名的文件夾:
* *類* 。 項目的已編譯.class文件。
* *報告* 。 構建生成的報告(例如測試報告)。
* *庫* 。 組裝的項目庫(通常是JAR和/或WAR文件)。
classes文件夾包含.class文件,這些文件是通過編譯Java代碼生成的。 具體來說,您應該找到HelloWorld.class和Greeter.class。
此時,該項目沒有任何庫依賴關系,因此 沒有任何內容 **dependency\_cache** 文件夾中 。
reports文件夾應包含項目上正在運行的單元測試的報告。 由于該項目尚無任何單元測試,因此該報告將變得毫無意義。
libs文件夾應包含以項目文件夾命名的JAR文件。 接下來,您將看到如何指定JAR的名稱及其版本。
## 聲明依賴
簡單的Hello World示例是完全獨立的,并且不依賴于任何其他庫。 但是,大多數應用程序都依賴于外部庫來處理常見和/或復雜的功能。
例如,假設除了說“ Hello World!”外,您還希望應用程序打印當前日期和時間。 您可以使用本機Java庫中的日期和時間工具,但是可以使用Joda Time庫使事情變得更有趣。
首先,將HelloWorld.java更改如下:
~~~
package hello;
import org.joda.time.LocalTime;
public class HelloWorld {
public static void main(String[] args) {
LocalTime currentTime = new LocalTime();
System.out.println("The current local time is: " + currentTime);
Greeter greeter = new Greeter();
System.out.println(greeter.sayHello());
}
}
~~~
這里 `HelloWorld` 使用Joda Time的 `LocalTime` 類以獲取并顯示當前時間。
如果你跑了 `gradle build` 要立即構建項目,構建將失敗,因為您尚未在構建中將Joda Time聲明為編譯依賴項。
對于初學者,您需要添加第三方庫的源。
~~~
repositories {
mavenCentral()
}
~~~
這 `repositories`塊指示構建應從Maven Central存儲庫中解決其依賴項。 Gradle在很大程度上依賴于Maven構建工具建立的許多約定和功能,包括使用Maven Central作為庫依賴源的選項。
現在我們已經準備好第三方庫了,讓我們聲明一下。
~~~
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
implementation "joda-time:joda-time:2.2"
testImplementation "junit:junit:4.12"
}
~~~
隨著 `dependencies`塊,您聲明Joda Time的單個依賴項。 具體來說,您要在joda-time組中要求(從右到左閱讀)joda-time庫的2.2版。
關于此依賴項要注意的另一件事是,它是一個 `compile`依賴關系,指示它在編譯時應該可用(如果正在構建WAR文件,則包含在WAR的/ WEB-INF / libs文件夾中)。 其他值得注意的依賴類型包括:
* `implementation`。 編譯項目代碼所需的依賴關系,但將在運行時由運行代碼的容器(例如Java Servlet API)提供。
* `testImplementation`。 用于編譯和運行測試的依賴關系,但對于構??建或運行項目的運行時代碼不是必需的。
最后,讓我們為我們的JAR工件指定名稱。
~~~
jar {
archiveBaseName = 'gs-gradle'
archiveVersion = '0.1.0'
}
~~~
這 `jar`塊指定如何命名JAR文件。 在這種情況下,它將呈現 `gs-gradle-0.1.0.jar`.
現在,如果您運行 `gradle build`,Gradle應該從Maven Central存儲庫中解決Joda Time依賴關系,并且構建將成功。
## 使用Gradle Wrapper建立您的專案
Gradle包裝器是開始Gradle構建的首選方法。 它由Windows的批處理腳本以及OS X和Linux的Shell腳本組成。 這些腳本使您可以運行Gradle構建,而無需在系統上安裝Gradle。 這曾經是添加到您的構建文件中的東西,但是已經被折疊到Gradle中,因此不再需要。 相反,您只需使用以下命令。
~~~
$ gradle wrapper --gradle-version 6.0.1
~~~
該任務完成后,您會注意到一些新文件。 這兩個腳本位于文件夾的根目錄中,而包裝jar和屬性文件已添加到新文件夾中。 `gradle/wrapper` 文件夾。
~~~
└── <project folder>
└── gradlew
└── gradlew.bat
└── gradle
└── wrapper
└── gradle-wrapper.jar
└── gradle-wrapper.properties
~~~
Gradle包裝器現在可用于構建您的項目。 將其添加到您的版本控制系統中,每個克隆您的項目的人都可以相同地構建它。 它的使用方式與Gradle的安裝版本完全相同。 運行包裝程序腳本以執行構建任務,就像之前一樣:
~~~
./gradlew build
~~~
第一次為指定版本的Gradle運行包裝程序時,它將下載并緩存該版本的Gradle二進制文件。 Gradle Wrapper文件旨在用于源代碼控制,因此任何人都可以構建項目,而無需首先安裝和配置特定版本的Gradle。
在這一階段,您將構建代碼。 您可以在此處查看結果:
~~~
build
├── classes
│?? └── main
│?? └── hello
│?? ├── Greeter.class
│?? └── HelloWorld.class
├── dependency-cache
├── libs
│?? └── gs-gradle-0.1.0.jar
└── tmp
└── jar
└── MANIFEST.MF
~~~
包括兩個預期的類文件 `Greeter` 和 `HelloWorld`,以及JAR文件。 快速瀏覽:
~~~
$ jar tvf build/libs/gs-gradle-0.1.0.jar
0 Fri May 30 16:02:32 CDT 2014 META-INF/
25 Fri May 30 16:02:32 CDT 2014 META-INF/MANIFEST.MF
0 Fri May 30 16:02:32 CDT 2014 hello/
369 Fri May 30 16:02:32 CDT 2014 hello/Greeter.class
988 Fri May 30 16:02:32 CDT 2014 hello/HelloWorld.class
~~~
類文件捆綁在一起。 需要注意的重要一點是,即使您將joda-time聲明為依賴項,該庫也不包含在此處。 而且JAR文件也不可運行。
為了使此代碼可運行,我們可以使用gradle的 `application`插入。 將此添加到您的 `build.gradle` 文件。
~~~
apply plugin: 'application'
mainClassName = 'hello.HelloWorld'
~~~
然后,您可以運行該應用程序!
~~~
$ ./gradlew run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
The current local time is: 16:16:20.544
Hello world!
BUILD SUCCESSFUL
Total time: 3.798 secs
~~~
捆綁依賴項需要更多的思考。 例如,如果我們正在構建WAR文件(一種通常與打包第三方依賴相關的格式),則可以使用gradle的 [WAR插件](https://www.gradle.org/docs/current/userguide/war_plugin.html) 。 如果您使用的是Spring Boot,并且想要一個可運行的JAR文件,則 [spring-boot-gradle-plugin](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-gradle) 非常方便。 在此階段,gradle對您的系統了解不足,無法做出選擇。 但是就目前而言,這應該足以開始使用gradle。
總結一下本指南的內容,以下是完成的內容 `build.gradle` 文件:
`build.gradle`
~~~
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
mainClassName = 'hello.HelloWorld'
// tag::repositories[]
repositories {
mavenCentral()
}
// end::repositories[]
// tag::jar[]
jar {
archiveBaseName = 'gs-gradle'
archiveVersion = '0.1.0'
}
// end::jar[]
// tag::dependencies[]
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
implementation "joda-time:joda-time:2.2"
testImplementation "junit:junit:4.12"
}
// end::dependencies[]
// tag::wrapper[]
// end::wrapper[]
~~~
這里嵌入了許多開始/結束注釋。 這樣就可以將構建文件的某些內容提取到本指南中,以進行上述詳細說明。 您的生產構建文件中不需要它們。
## 概括
恭喜你! 現在,您已經創建了一個簡單而有效的Gradle構建文件,用于構建Java項目。
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解