gradle-spring-boot-integration

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Works with build.gradle.kts, application.yml, and Dockerfile configurations.
支持build.gradle.kts、application.yml和Dockerfile配置。

Gradle Spring Boot Integration

Gradle与Spring Boot集成

Table of Contents

目录

Purpose

用途

Set up and configure Spring Boot projects in Gradle with proper JAR creation, Docker optimization, and multi-module support. This skill covers bootable JAR setup, layered JARs for optimal Docker caching, and Spring Boot-specific task configuration.
在Gradle中搭建并配置Spring Boot项目,支持正确的JAR创建、Docker优化和多模块开发。本技能涵盖可执行JAR设置、用于Docker缓存优化的分层JAR,以及Spring Boot专属任务配置。

When to Use

适用场景

Use this skill when you need to:
  • Set up new Spring Boot projects with Gradle
  • Create executable JAR files for Spring Boot applications
  • Configure layered JARs for optimized Docker builds
  • Set up multi-module projects with shared libraries
  • Configure Spring Boot DevTools for hot reload
  • Inject build information into application.yml
  • Set up Spring Boot Actuator for monitoring
  • Configure testing with Spring Boot test starters
在以下场景中使用本技能:
  • 使用Gradle搭建新的Spring Boot项目
  • 为Spring Boot应用创建可执行JAR文件
  • 配置分层JAR以优化Docker构建
  • 搭建包含共享库的多模块项目
  • 配置Spring Boot DevTools实现热重载
  • 向application.yml中注入构建信息
  • 配置Spring Boot Actuator实现监控
  • 使用Spring Boot测试启动器配置测试

Quick Start

快速开始

Minimal Spring Boot setup in
build.gradle.kts
:
kotlin
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.example"
version = "0.0.1-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}
Run and build:
bash
./gradlew bootRun                                    # Run locally
./gradlew bootJar                                    # Create executable JAR
./gradlew bootRun --args='--spring.profiles.active=dev'  # Run with profile
build.gradle.kts
中的最简Spring Boot配置:
kotlin
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.example"
version = "0.0.1-SNAPSHOT"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}
运行与构建:
bash
./gradlew bootRun                                    # 本地运行
./gradlew bootJar                                    # 创建可执行JAR
./gradlew bootRun --args='--spring.profiles.active=dev'  # 带配置文件运行

Instructions

操作步骤

Step 1: Apply Spring Boot Plugin

步骤1:应用Spring Boot插件

Configure the Spring Boot Gradle plugin for your project type:
kotlin
// build.gradle.kts - Web Service (creates bootable JAR)
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}
Key plugins:
  • org.springframework.boot
    : Creates executable JARs, provides bootRun task
  • io.spring.dependency-management
    : Automatically imports Spring Boot BOM
为你的项目类型配置Spring Boot Gradle插件:
kotlin
// build.gradle.kts - Web服务(创建可执行JAR)
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}
核心插件:
  • org.springframework.boot
    : 创建可执行JAR,提供bootRun任务
  • io.spring.dependency-management
    : 自动导入Spring Boot BOM

Step 2: Configure Java Toolchain

步骤2:配置Java工具链

Specify Java version for consistency:
kotlin
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}
指定Java版本以保持一致性:
kotlin
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

Step 3: Add Spring Boot Dependencies

步骤3:添加Spring Boot依赖

Use the BOM automatically imported by the plugin:
kotlin
dependencies {
    // Spring Boot starter (no version needed - from BOM)
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")

    // Development only (DevTools for hot reload)
    developmentOnly("org.springframework.boot:spring-boot-devtools")

    // Test dependencies
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

// Enable JUnit 5
tasks.test {
    useJUnitPlatform()
}
使用插件自动导入的BOM:
kotlin
dependencies {
    // Spring Boot启动器(无需版本号 - 来自BOM)
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")

    // 仅开发环境使用(DevTools实现热重载)
    developmentOnly("org.springframework.boot:spring-boot-devtools")

    // 测试依赖
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

// 启用JUnit 5
tasks.test {
    useJUnitPlatform()
}

Step 4: Configure Bootable JAR Creation

步骤4:配置可执行JAR创建

For services (executable JARs):
kotlin
tasks.bootJar {
    enabled = true
    archiveClassifier = ""  // No classifier for main artifact
}

tasks.jar {
    enabled = false  // Disable plain JAR
}
For libraries (plain JARs):
kotlin
tasks.bootJar {
    enabled = false  // Not executable
}

tasks.jar {
    enabled = true  // Create library JAR
}
服务项目(可执行JAR):
kotlin
tasks.bootJar {
    enabled = true
    archiveClassifier = ""  // 主产物无分类器
}

tasks.jar {
    enabled = false  // 禁用普通JAR
}
库项目(普通JAR):
kotlin
tasks.bootJar {
    enabled = false  // 不可执行
}

tasks.jar {
    enabled = true  // 创建库JAR
}

Step 5: Enable Layered JARs for Docker Optimization

步骤5:启用分层JAR以优化Docker

Layered JARs separate dependencies by change frequency for better Docker caching:
kotlin
tasks.bootJar {
    enabled = true

    layered {
        enabled = true
        application {
            enabled = true
        }
        dependencies {
            enabled = true
        }
        springBootLoader {
            enabled = true
        }
        snapshot {
            enabled = true
        }
    }
}
Layers (in order):
  1. dependencies: Rarely-changing external dependencies
  2. spring-boot-loader: Spring Boot loader classes
  3. snapshot-dependencies: Snapshot/SNAPSHOT versions (changing)
  4. application: Application classes (most frequently changing)
Extract layers in Dockerfile:
dockerfile
FROM eclipse-temurin:21-jre-alpine AS builder
WORKDIR /builder
COPY build/libs/app.jar .
RUN java -Djarmode=layertools -jar app.jar extract

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=builder /builder/dependencies ./
COPY --from=builder /builder/spring-boot-loader ./
COPY --from=builder /builder/snapshot-dependencies ./
COPY --from=builder /builder/application ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]
分层JAR按变更频率分离依赖,提升Docker缓存效率:
kotlin
tasks.bootJar {
    enabled = true

    layered {
        enabled = true
        application {
            enabled = true
        }
        dependencies {
            enabled = true
        }
        springBootLoader {
            enabled = true
        }
        snapshot {
            enabled = true
        }
    }
}
分层顺序:
  1. dependencies: 极少变更的外部依赖
  2. spring-boot-loader: Spring Boot加载器类
  3. snapshot-dependencies: 快照/SNAPSHOT版本(易变更)
  4. application: 应用类(变更最频繁)
在Dockerfile中提取分层:
dockerfile
FROM eclipse-temurin:21-jre-alpine AS builder
WORKDIR /builder
COPY build/libs/app.jar .
RUN java -Djarmode=layertools -jar app.jar extract

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY --from=builder /builder/dependencies ./
COPY --from=builder /builder/spring-boot-loader ./
COPY --from=builder /builder/snapshot-dependencies ./
COPY --from=builder /builder/application ./
ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]

Step 6: Configure Application Properties

步骤6:配置应用属性

Inject build information into
application.yml
:
kotlin
tasks.processResources {
    filesMatching("application.yml") {
        expand(
            "version" to project.version,
            "name" to project.name,
            "timestamp" to System.currentTimeMillis()
        )
    }
}
In
application.yml
:
yaml
spring:
  application:
    name: ${name}

info:
  app:
    name: ${name}
    version: ${version}
    build-timestamp: ${timestamp}
application.yml
中注入构建信息:
kotlin
tasks.processResources {
    filesMatching("application.yml") {
        expand(
            "version" to project.version,
            "name" to project.name,
            "timestamp" to System.currentTimeMillis()
        )
    }
}
application.yml
中配置:
yaml
spring:
  application:
    name: ${name}

info:
  app:
    name: ${name}
    version: ${version}
    build-timestamp: ${timestamp}

Step 7: Set Up Spring Boot DevTools for Local Development

步骤7:配置Spring Boot DevTools用于本地开发

Enable hot reload during development:
kotlin
dependencies {
    developmentOnly("org.springframework.boot:spring-boot-devtools")
}
Trigger reload:
  • IntelliJ: Build Project (Cmd/Ctrl + F9)
  • Eclipse: Save file
  • CLI: Run
    ./gradlew compileJava
    in separate terminal
启用开发时热重载:
kotlin
dependencies {
    developmentOnly("org.springframework.boot:spring-boot-devtools")
}
触发重载:
  • IntelliJ: 构建项目(Cmd/Ctrl + F9)
  • Eclipse: 保存文件
  • CLI: 在单独终端运行
    ./gradlew compileJava

Step 8: Configure Actuator for Monitoring

步骤8:配置Actuator实现监控

Add actuator endpoints and metrics:
kotlin
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("io.micrometer:micrometer-registry-prometheus")
}
In
application.yml
:
yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus,metrics,env
  metrics:
    export:
      prometheus:
        enabled: true
  endpoint:
    health:
      show-details: always
添加Actuator端点与指标:
kotlin
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    implementation("io.micrometer:micrometer-registry-prometheus")
}
application.yml
中配置:
yaml
management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus,metrics,env
  metrics:
    export:
      prometheus:
        enabled: true
  endpoint:
    health:
      show-details: always

Examples

示例

Example 1: Simple Web Service

示例1:简单Web服务

kotlin
// build.gradle.kts
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.waitrose"
version = "1.0.0"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}

tasks.bootJar {
    enabled = true
}

tasks.jar {
    enabled = false
}
Build and run:
bash
./gradlew bootJar              # Create JAR: build/libs/app-1.0.0.jar
java -jar build/libs/app-1.0.0.jar  # Run JAR
For advanced examples including multi-module setups, layered JARs with Docker, build info injection, and testing configurations, see examples/advanced-examples.md.
kotlin
// build.gradle.kts
plugins {
    id("java")
    id("org.springframework.boot") version "3.5.5"
    id("io.spring.dependency-management") version "1.1.7"
}

group = "com.waitrose"
version = "1.0.0"

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-actuator")

    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test {
    useJUnitPlatform()
}

tasks.bootJar {
    enabled = true
}

tasks.jar {
    enabled = false
}
构建与运行:
bash
./gradlew bootJar              # 创建JAR: build/libs/app-1.0.0.jar
java -jar build/libs/app-1.0.0.jar  # 运行JAR
如需包含多模块配置、带Docker的分层JAR、构建信息注入和测试配置的进阶示例,请查看examples/advanced-examples.md

Commands Reference

命令参考

See references/commands-and-troubleshooting.md for complete command reference and troubleshooting guide.
完整的命令参考与故障排除指南请查看references/commands-and-troubleshooting.md

See Also

相关链接