Appearance
Groovy DSL 基础
Groovy DSL 是 Gradle 的传统构建语言,语法简洁灵活,无需严格的类型声明。
Groovy 基础语法
变量与类型
groovy
// 动态类型(def 关键字)
def name = "Gradle"
def version = 8.5
def isRelease = true
// 字符串(单引号或双引号)
def singleQuote = 'Hello'
def doubleQuote = "Hello, ${name}!" // 支持插值
// 多行字符串
def multiLine = """
This is
a multi-line
string
"""
// 列表
def list = ['a', 'b', 'c']
println list[0] // 'a'
println list.size()
// Map
def map = [name: 'Gradle', version: '8.5']
println map.name // Gradle
println map['version'] // 8.5方法调用(括号可选)
groovy
// Groovy 中方法调用括号可以省略(这是 Gradle DSL 的基础)
println("Hello") // 标准写法
println "Hello" // Groovy 简写
// apply plugin: 'java' 等价于
apply(plugin: 'java')闭包(Closure)
Groovy 闭包是 Gradle DSL 的核心:
groovy
// 基础闭包
def greet = { name ->
println "Hello, ${name}!"
}
greet("World")
// 闭包作为参数传递(Gradle 配置块的原理)
def configure = { closure ->
closure.call()
}
configure {
println "在闭包中执行"
}Gradle Groovy DSL 语法
build.gradle 基本结构
groovy
// build.gradle
// 1. 插件声明
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.0'
id 'io.spring.dependency-management' version '1.1.4'
}
// 2. 项目信息
group = 'com.example'
version = '1.0.0'
description = '示例项目'
// 3. Java 配置
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
// 4. 仓库配置
repositories {
mavenCentral()
maven { url 'https://maven.aliyun.com/repository/public' }
}
// 5. 依赖
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.mysql:mysql-connector-j'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
// 6. 任务配置
tasks.named('test') {
useJUnitPlatform()
}
// 7. 自定义任务
task printInfo {
group = 'custom'
description = '打印项目信息'
doLast {
println "项目名称: ${project.name}"
println "项目版本: ${project.version}"
}
}属性与变量
groovy
// 局部变量(仅在当前脚本使用)
def springBootVersion = '3.2.0'
// ext 扩展属性(可被其他脚本访问)
ext {
springBootVersion = '3.2.0'
junitVersion = '5.10.1'
}
// 使用方式
dependencies {
implementation "org.springframework.boot:spring-boot-starter-web:${springBootVersion}"
}条件逻辑
groovy
// 根据环境配置不同行为
def isProduction = project.hasProperty('prod')
tasks.named('jar') {
if (isProduction) {
archiveClassifier.set('')
}
}
// 根据操作系统
if (org.gradle.internal.os.OperatingSystem.current().isWindows()) {
tasks.register('startServer', Exec) {
commandLine 'cmd', '/c', 'start.bat'
}
} else {
tasks.register('startServer', Exec) {
commandLine './start.sh'
}
}多项目配置
groovy
// 根项目 build.gradle
// 所有项目(包括根项目)的配置
allprojects {
group = 'com.example'
version = '1.0.0'
repositories {
mavenCentral()
}
}
// 所有子项目的配置
subprojects {
apply plugin: 'java'
java {
sourceCompatibility = JavaVersion.VERSION_17
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.1'
}
tasks.named('test') {
useJUnitPlatform()
}
}
// 针对特定子项目配置
project(':web') {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web:3.2.0'
}
}文件操作
groovy
// 复制文件
task copyConfig(type: Copy) {
from 'src/config'
into "${buildDir}/config"
include '*.yml'
exclude 'test*.yml'
}
// 替换文件内容中的占位符
task processConfig(type: Copy) {
from 'src/config'
into "${buildDir}/config"
filter { line ->
line.replace('@VERSION@', version)
}
}
// ZIP 打包
task packageApp(type: Zip) {
archiveFileName = "app-${version}.zip"
destinationDirectory = file("${buildDir}/dist")
from 'src/main/resources'
from tasks.jar
}Groovy DSL 使用技巧
动态任务创建
groovy
// 批量创建任务
['dev', 'test', 'prod'].each { env ->
task "deploy${env.capitalize()}" {
group = 'deploy'
description = "部署到 ${env} 环境"
doLast {
println "正在部署到 ${env}..."
}
}
}
// 生成:deployDev, deployTest, deployProd读取外部配置
groovy
// 从 properties 文件读取配置
def configFile = file('config/database.properties')
def config = new Properties()
configFile.withInputStream { config.load(it) }
ext {
dbUrl = config['db.url']
dbUser = config['db.user']
}访问系统属性和环境变量
groovy
// 系统属性(-D 参数)
def myProp = System.getProperty('my.property', 'default')
// 环境变量
def apiKey = System.getenv('API_KEY') ?: 'default-key'
// Gradle 项目属性(-P 参数或 gradle.properties)
if (project.hasProperty('releaseVersion')) {
version = project.releaseVersion
}常见 Groovy DSL 模式
buildscript 块(旧式插件声明)
groovy
// 旧式写法(不推荐,但常见于旧项目)
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:3.2.0'
}
}
apply plugin: 'org.springframework.boot'新式 plugins 块(推荐)
groovy
// 推荐写法
plugins {
id 'org.springframework.boot' version '3.2.0'
}下一步
- Kotlin DSL 基础 - 对比学习 Kotlin DSL
- 属性与变量 - 深入了解属性管理
- 任务基础 - 学习任务定义