构建脚本可以是使用 Groovy 编写的 build.gradle 文件,也可以是使用 Kotlin 编写的 build.gradle.kts 文件。

Groovy DSL 和 Kotlin DSL 是 Gradle 脚本唯一接受的语言。

在多项目构建中,每个子项目通常都有自己的构建文件,位于其根目录中。

在构建脚本中,您通常会指定

插件:扩展 Gradle 功能的工具,用于编译代码、运行测试或打包 artifact 等任务。

依赖:您的项目使用的外部库和工具。

具体来说,构建脚本包含两种主要类型的依赖

Gradle 和构建脚本依赖:这包括 Gradle 本身或构建脚本逻辑所需的插件和库。

项目依赖:您的项目源代码正确编译和运行所需的库。

让我们看一个例子并将其分解

app/build.gradle.kts

plugins { (1)

// Apply the application plugin to add support for building a CLI application in Java.

application

}

dependencies { (2)

// Use JUnit Jupiter for testing.

testImplementation(libs.junit.jupiter)

testRuntimeOnly("org.junit.platform:junit-platform-launcher")

// This dependency is used by the application.

implementation(libs.guava)

}

application { (3)

// Define the main class for the application.

mainClass = "org.example.App"

}

app/build.gradle

plugins { (1)

// Apply the application plugin to add support for building a CLI application in Java.

id 'application'

}

dependencies { (2)

// Use JUnit Jupiter for testing.

testImplementation libs.junit.jupiter

testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

// This dependency is used by the application.

implementation libs.guava

}

application { (3)

// Define the main class for the application.

mainClass = 'org.example.App'

}

1

添加插件。

2

添加依赖。

3

使用约定属性。