Skip to content

Settings 深度解析

源:Gradle 官方文档 - Settings File Basics | Settings DSL

settings.gradle.kts 是 Gradle 构建的起点,负责初始化项目结构、配置插件仓库和依赖解析策略。在现代多模块项目中,它是最重要的配置中心。

Settings 文件基础

文件位置和执行时机

位置:项目根目录的 settings.gradle.kts

执行时机:Initialization 阶段(构建生命周期的第一阶段)

作用

  • 定义项目名称
  • 声明子项目
  • 配置插件管理
  • 配置依赖解析策略
  • 配置版本目录

基本结构

kotlin
// settings.gradle.kts
rootProject.name = "my-app"

include(":app")
include(":core")
include(":feature-login")

项目定义

rootProject 配置

kotlin
// 设置根项目名称
rootProject.name = "my-project"

// 访问根项目目录
println(rootProject.projectDir)

// 访问构建目录
println(rootProject.buildDir)

include 子项目

基本用法

kotlin
include(":app")
include(":core")
include(":feature-login")

批量包含

kotlin
include(
    ":app",
    ":core",
    ":feature-login",
    ":feature-home"
)

嵌套项目

kotlin
include(":libraries:networking")
include(":libraries:database")
include(":features:login")
include(":features:home")

project 自定义路径

修改子项目的物理目录:

kotlin
include(":app")
project(":app").projectDir = file("android-app")

项目结构:

my-project/
├── settings.gradle.kts
├── android-app/          # 实际目录
│   └── build.gradle.kts

pluginManagement 插件管理

配置插件仓库

集中配置所有模块的插件搜索仓库:

kotlin
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

仓库优先级:按声明顺序搜索,找到即停止。

插件版本管理

统一插件版本

kotlin
pluginManagement {
    plugins {
        id("com.android.application") version "8.7.3"
        id("com.android.library") version "8.7.3"
        kotlin("android") version "2.1.0"
        kotlin("kapt") version "2.1.0"
    }
}

使用时无需指定版本:

kotlin
// app/build.gradle.kts
plugins {
    id("com.android.application")  // 版本已在 settings 中定义
    kotlin("android")
}

插件解析策略

自定义插件坐标

kotlin
pluginManagement {
    resolutionStrategy {
        eachPlugin {
            if (requested.id.id == "my-plugin") {
                useModule("com.example:my-plugin:${requested.version}")
            }
        }
    }
}

dependencyResolutionManagement 依赖解析管理

集中式仓库管理 推荐

强制所有模块使用统一的仓库配置:

kotlin
dependencyResolutionManagement {
    // 强制模式:禁止子模块单独定义仓库
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    
    repositories {
        google()
        mavenCentral()
    }
}

repositoriesMode 选项

  • PREFER_PROJECT:优先使用项目定义的仓库
  • PREFER_SETTINGS:优先使用 settings 定义的仓库
  • FAIL_ON_PROJECT_REPOS:禁止项目单独定义仓库(推荐)

优势

  • 统一管理仓库配置
  • 避免重复声明
  • 提升构建性能
  • 便于企业统一管控

版本目录集成

配置 Version Catalog:

kotlin
dependencyResolutionManagement {
    versionCatalogs {
        create("libs") {
            from(files("gradle/libs.versions.toml"))
        }
    }
}

使用多个版本目录

kotlin
dependencyResolutionManagement {
    versionCatalogs {
        create("libs") {
            from(files("gradle/libs.versions.toml"))
        }
        create("testLibs") {
            from(files("gradle/test-libs.versions.toml"))
        }
    }
}

依赖替换规则

全局依赖替换:

kotlin
dependencyResolutionManagement {
    components {
        all {
            allVariants {
                withDependencies {
                    // 替换特定依赖
                    if (requested.group == "com.example" && requested.name == "old-lib") {
                        useTarget("com.example:new-lib:${requested.version}")
                    }
                }
            }
        }
    }
}

includeBuild 复合构建

基本用法

包含独立的 Gradle 项目:

kotlin
includeBuild("../shared-library")
includeBuild("build-logic")

目录结构

workspace/
├── my-app/
│   └── settings.gradle.kts
├── shared-library/
│   ├── settings.gradle.kts
│   └── build.gradle.kts
└── build-logic/
    ├── settings.gradle.kts
    └── build.gradle.kts

依赖替换

自动替换二进制依赖为源码依赖:

kotlin
// my-app/settings.gradle.kts
includeBuild("../shared-library") {
    dependencySubstitution {
        substitute(module("com.example:shared-library"))
            .using(project(":"))
    }
}

使用:

kotlin
// app/build.gradle.kts
dependencies {
    // 自动使用 includeBuild 的源码
    implementation("com.example:shared-library:1.0.0")
}

优势

  • 源码调试方便
  • 无需发布即可测试
  • 团队协作更灵活

enableFeaturePreview 特性预览

启用实验性功能:

kotlin
enableFeaturePreview("STABLE_CONFIGURATION_CACHE")
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

常用特性

TYPESAFE_PROJECT_ACCESSORS 推荐

kotlin
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

启用后可以使用类型安全的项目引用:

kotlin
// app/build.gradle.kts
dependencies {
    implementation(projects.core)  // 类型安全
    implementation(projects.features.login)
}

构建监听器

gradle 对象

在 settings.gradle.kts 中可以访问 gradle 对象:

kotlin
gradle.addBuildListener(object : BuildListener {
    override fun buildStarted(gradle: Gradle) {
        println("Build started")
    }
    
    override fun settingsEvaluated(settings: Settings) {
        println("Settings evaluated: ${settings.rootProject.name}")
    }
    
    override fun projectsLoaded(gradle: Gradle) {
        println("Projects loaded: ${gradle.rootProject.childProjects.size} modules")
    }
    
    override fun projectsEvaluated(gradle: Gradle) {
        println("Projects evaluated")
    }
    
    override fun buildFinished(result: BuildResult) {
        if (result.failure != null) {
            println("Build failed: ${result.failure}")
        } else {
            println("Build succeeded")
        }
    }
})

生命周期钩子

监听项目加载完成

kotlin
gradle.projectsLoaded {
    println("Total projects: ${gradle.rootProject.allprojects.size}")
}

监听任务图构建

kotlin
gradle.taskGraph.whenReady { graph ->
    val tasks = graph.allTasks.joinToString { it.path }
    println("Will execute: $tasks")
}

buildCache 构建缓存

本地缓存

kotlin
buildCache {
    local {
        isEnabled = true
        directory = file("${rootDir}/.gradle/build-cache")
        removeUnusedEntriesAfterDays = 30
    }
}

远程缓存 企业级

kotlin
buildCache {
    local {
        isEnabled = true
    }
    
    remote<HttpBuildCache> {
        url = uri("https://cache.example.com/cache/")
        isPush = System.getenv("CI") == "true"
        
        credentials {
            username = System.getenv("CACHE_USERNAME")
            password = System.getenv("CACHE_PASSWORD")
        }
    }
}

配置逻辑

  • CI 环境:推送缓存
  • 本地开发:仅拉取缓存

Settings 插件 AGP 8.0+

Android Gradle Plugin 8.0+ 引入 Settings 插件。

启用 Settings 插件

kotlin
plugins {
    id("com.android.settings") version "8.7.3"
}

配置 Android 设置

kotlin
android {
    minSdk = 24
    compileSdk = 34
}

实用配置示例

完整的企业级配置

kotlin
// settings.gradle.kts
pluginManagement {
    repositories {
        maven {
            url = uri("https://repo.company.com/gradle-plugins")
            credentials {
                username = System.getenv("REPO_USERNAME")
                password = System.getenv("REPO_PASSWORD")
            }
        }
        google()
        mavenCentral()
        gradlePluginPortal()
    }
    
    plugins {
        id("com.android.application") version "8.7.3"
        id("com.android.library") version "8.7.3"
        kotlin("android") version "2.1.0"
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    
    repositories {
        maven {
            url = uri("https://repo.company.com/maven")
            credentials {
                username = System.getenv("REPO_USERNAME")
                password = System.getenv("REPO_PASSWORD")
            }
        }
        google()
        mavenCentral()
    }
    
    versionCatalogs {
        create("libs") {
            from(files("gradle/libs.versions.toml"))
        }
    }
}

buildCache {
    local {
        isEnabled = true
    }
    
    remote<HttpBuildCache> {
        url = uri("https://cache.company.com/")
        isPush = System.getenv("CI") == "true"
        credentials {
            username = System.getenv("CACHE_USERNAME")
            password = System.getenv("CACHE_PASSWORD")
        }
    }
}

rootProject.name = "my-app"

include(":app")
include(":core")
include(":features:login")
include(":features:home")

includeBuild("build-logic")

enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

Android 多模块配置

kotlin
// settings.gradle.kts
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
    versionCatalogs {
        create("libs") {
            from(files("gradle/libs.versions.toml"))
        }
    }
}

rootProject.name = "MyAndroidApp"

include(":app")
include(":core:common")
include(":core:network")
include(":core:database")
include(":features:login")
include(":features:home")
include(":features:profile")

enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")

最佳实践

集中式仓库管理

  • 使用 dependencyResolutionManagement
  • 设置 FAIL_ON_PROJECT_REPOS
  • 避免在子模块重复配置

版本目录

  • 在 settings 中配置 Version Catalog
  • 统一管理依赖版本
  • 提升维护性

复合构建

  • 使用 includeBuild 管理独立插件
  • 便于源码调试
  • 适合大型项目

构建缓存

  • 启用本地缓存
  • CI 环境配置远程缓存
  • 定期清理旧缓存

插件版本管理

  • pluginManagement 中统一版本
  • 子模块无需重复声明版本
  • 便于升级维护

类型安全访问

  • 启用 TYPESAFE_PROJECT_ACCESSORS
  • 使用 projects.xxx 引用子项目
  • 编译期检查,避免错误

监控构建过程

  • 使用生命周期监听器
  • 记录关键信息
  • 定位性能问题