Skip to content

settings.gradle.kts 详解

settings.gradle.kts 是 Gradle 构建的入口文件,在初始化阶段执行,定义了项目结构和全局配置。

基本结构

kotlin
// settings.gradle.kts

// 1. 插件管理
pluginManagement {
    repositories {
        gradlePluginPortal()
        mavenCentral()
        google()
    }
    
    // 统一管理插件版本(避免在各子项目中重复声明版本)
    plugins {
        id("org.springframework.boot") version "3.2.0"
        id("io.spring.dependency-management") version "1.1.4"
        kotlin("jvm") version "1.9.22"
    }
}

// 2. 依赖解析管理(推荐)
dependencyResolutionManagement {
    // FAIL_ON_PROJECT_REPOS:禁止子项目自己声明仓库
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    
    repositories {
        mavenCentral()
        google()
    }
    
    // 版本目录
    versionCatalogs {
        create("libs") {
            from(files("gradle/libs.versions.toml"))
        }
    }
}

// 3. 根项目名称
rootProject.name = "my-company-app"

// 4. 子项目声明
include("core", "web", "api")
include("service:auth", "service:order")

// 5. 自定义子项目目录(非约定目录)
project(":legacy-module").projectDir = file("../legacy/module")

include 语法

kotlin
// 基本包含
include("core")                // → core/ 目录
include("service:auth")        // → service/auth/ 目录(冒号对应目录分隔)

// 批量包含
include("module-a", "module-b", "module-c")

// 带路径映射
includeBuild("../shared-lib")  // 复合构建(Composite Build)

pluginManagement 详解

kotlin
pluginManagement {
    // 插件解析规则(插件别名或重定向)
    resolutionStrategy {
        eachPlugin {
            if (requested.id.namespace == "org.springframework") {
                useVersion("3.2.0")
            }
        }
    }
    
    repositories {
        // 先从私有仓库找
        maven { url = uri("https://private.example.com/plugins") }
        gradlePluginPortal()
        mavenCentral()
    }
}

条件包含子项目

kotlin
// 根据属性决定是否包含某个子项目
if (file("experimental").exists()) {
    include("experimental")
}

// 根据系统属性
if (System.getProperty("includeLegacy") == "true") {
    include("legacy")
}

功能预览标志

kotlin
// 启用 Gradle 预览功能
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")  // 类型安全的项目引用

// 使用后可以这样引用子项目
// implementation(projects.core)  代替 implementation(project(":core"))

下一步