首先使用 Gradle init 创建 Java 应用程序,了解创作 Gradle 的基础知识。

在本节中,您将:

  • 初始化一个Java项目

  • 检查目录布局

  • 运行 Java 应用程序

  • 生成构建扫描

  • 将应用程序打包到存档中

步骤 0. 开始之前

  1. 确保您已安装 Gradle

  2. 安装IntelliJ IDEA。社区版是 IntelliJ IDEA 的免费版本。

步骤 1. 初始化项目

authoring-tutorial创建一个名为并进入其中的新目录cd

$ mkdir authoring-tutorial
$ cd authoring-tutorial

带参数运行gradle init以生成 Java 应用程序:

$ gradle init --type java-application  --dsl kotlin
$ gradle init --type java-application  --dsl groovy

对于任何其他提示,请选择默认值。

在本教程中,所有示例均基于 macOS。

步骤 2. 了解目录布局

项目根目录包含项目中的所有源文件。

完成 Gradle 后init,目录应如下所示:

.
├── gradle                              (1)
    ├── libs.version.toml               (2)
│   └── wrapper
├── gradlew                             (3)
├── gradlew.bat                         (3)
├── settings.gradle.kts                 (4)
└── app
    ├── build.gradle.kts                (5)
    └── src
        ├── main
        │   └── java                    (6)
        │       └── demo
        │           └── App.java
        └── test
            └── java                    (7)
                └── demo
                    └── AppTest.java
1 Generated folder for wrapper files
2 Version catalog for dependencies
3 Gradle wrapper start scripts
4 Settings file to define build name and subprojects
5 Build script for app subproject
6 Default Java source folder for app subproject
7 Default Java test source folder for app subproject
.
├── gradle                              (1)
    ├── libs.version.toml               (2)
│   └── wrapper
├── gradlew                             (3)
├── gradlew.bat                         (3)
├── settings.gradle                     (4)
└── app
    ├── build.gradle                    (5)
    └── src
        ├── main
        │   └── java                    (6)
        │       └── demo
        │           └── App.java
        └── test
            └── java                    (7)
                └── demo
                    └── AppTest.java
1 Generated folder for wrapper files
2 Version catalog for dependencies
3 Gradle wrapper start scripts
4 Settings file to define build name and subprojects
5 Build script for app subproject
6 Default Java source folder for app subproject
7 Default Java test source folder for app subproject

authoring-tutorial文件夹是项目根目录。根项目目录内包含一个或多个子项目、构建脚本和 Gradle 包装器。

虽然 Gradle Wrapper 位于根项目本地,但 Gradle 可执行文件位于GRADLE_USER_HOME.

GRADLE_USER_HOME默认为 的,USER_HOME/.gradle也是 Gradle 存储其全局配置属性、初始化脚本、缓存、日志文件等的地方。

步骤 3. 查看 Gradle 文件

settings.gradle(.kts)文件有两行有趣的内容:

settings.gradle.kts
rootProject.name = "authoring-tutorial"
include("app")
settings.gradle
rootProject.name = 'authoring-tutorial'
include('app')
  • rootProject.name为构建分配一个名称,覆盖以目录名称命名构建的默认行为。

  • include("app")定义构建由一个名为 的子项目组成app,该子项目包含其自己的源代码和构建逻辑。

可以通过附加语句添加更多子项目include()

我们的构建包含一个名为app代表我们正在构建的 Java 应用程序的子项目。它在文件中配置app/build.gradle(.kts)

build.gradle.kts
plugins {
    id("application")                                               (1)
}

repositories {
    mavenCentral()                                                  (2)
}

dependencies {
    testImplementation(libs.junit.jupiter)                          (3)
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
    implementation(libs.guava)                                      (4)
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)                (5)
    }
}

application {
    mainClass = "org.example.App"                                   (6)
}

tasks.named<Test>("test") {
    useJUnitPlatform()                                              (7)
}
1 Apply the application plugin to add support for building a CLI application in Java.
2 Use Maven Central for resolving dependencies.
3 Use JUnit Jupiter for testing (using the version catalog).
4 This dependency is used by the application (referred using the version catalog).
5 Define the toolchain version.
6 Define the main class for the application.
7 Use JUnit Platform for unit tests.
plugins {
    id 'application'                                                (1)
}

repositories {
    mavenCentral()                                                  (2)
}

dependencies {
    testImplementation libs.junit.jupiter                           (3)
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
    implementation libs.guava                                       (4)
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)                (5)
    }
}

application {
    mainClass = 'org.example.App'                                   (6)
}

tasks.named('test') {
    useJUnitPlatform()                                              (7)
}
1 Apply the application plugin to add support for building a CLI application in Java.
2 Use Maven Central for resolving dependencies.
3 Use JUnit Jupiter for testing (using the version catalog).
4 This dependency is used by the application (referred using the version catalog).
5 Define the toolchain version.
6 Define the main class for the application.
7 Use JUnit Platform for unit tests.

子项目目录中的构建脚本声明了代码需要组装和测试的app依赖项。app

步骤 4. 检查代码

该文件app/src/main/java/authoring/tutorial/App.java包含项目的主类:

应用程序.java
package authoring.tutorial;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        System.out.println(new App().getGreeting());
    }
}

该代码在屏幕上打印出简单的“Hello World”问候语。

测试课程可在app/src/test/java/authoring/tutorial/AppTest.java

应用程序测试.java
package authoring.tutorial;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class AppTest {
    @Test void appHasAGreeting() {
        App classUnderTest = new App();
        assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");
    }
}

生成的测试类有一个JUnit Jupiter测试。该测试实例化该类App,调用它的方法,并检查它是否返回预期值。

步骤 5. 运行应用程序

由 自动添加的应用程序插件gradle init有助于创建可执行的 JVM 应用程序:

plugins {
    id("application")
}
plugins {
    id 'application'
}

应用应用程序插件会隐式应用 Java 插件,并将assemblebuild、 和等任务添加run到我们的项目中。

借助该application插件,您可以直接从命令行运行应用程序。该run任务告诉 Gradle 执行分配main给该属性的类中的方法mainClass

$ ./gradlew run

> Task :app:run
Hello World!

BUILD SUCCESSFUL in 998ms
2 actionable tasks: 2 executed

步骤 6. 捆绑应用程序

application插件为您打包应用程序及其所有依赖项。该存档还将包含一个脚本,用于使用单个命令启动应用程序。

运行./gradlew build

$ ./gradlew build

> Task :app:compileJava
> Task :app:processResources NO-SOURCE
> Task :app:classes
> Task :app:jar
> Task :app:startScripts
> Task :app:distTar
> Task :app:distZip
> Task :app:assemble
> Task :app:compileTestJava
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses
> Task :app:test
> Task :app:check
> Task :app:build

BUILD SUCCESSFUL in 5s

如果您运行如上所示的完整构建,Gradle 将以两种格式生成存档:app/build/distributions/app.tarapp/build/distributions/app.zip.

步骤 6. 发布构建扫描

了解更多有关构建在幕后所做的事情的最佳方法是发布构建扫描。为此,请build使用该标志再次运行该任务--scan

$ ./gradlew build --scan
> Task :app:compileJava UP-TO-DATE
> Task :app:processResources NO-SOURCE
> Task :app:classes UP-TO-DATE
> Task :app:jar UP-TO-DATE
> Task :app:startScripts UP-TO-DATE
> Task :app:distTar UP-TO-DATE
> Task :app:distZip UP-TO-DATE
> Task :app:assemble UP-TO-DATE
> Task :app:compileTestJava UP-TO-DATE
> Task :app:processTestResources NO-SOURCE
> Task :app:testClasses UP-TO-DATE
> Task :app:test UP-TO-DATE
> Task :app:check UP-TO-DATE
> Task :app:build UP-TO-DATE

BUILD SUCCESSFUL in 1s
7 actionable tasks: 7 up-to-date
Resolving local hostname is slow, see https://gradle.com/help/gradle-slow-host-name

Publishing a build scan to scans.gradle.com requires accepting the Gradle Terms of Service defined at https://gradle.com/terms-of-service. Do you accept these terms? [yes, no] yes

Gradle Terms of Service accepted.

Publishing build scan...
https://gradle.com/s/link

单击链接并探索执行了哪些任务、下载了哪些依赖项以及更多详细信息:

构建扫描 3

下一步: 构建生命周期>>