迁移到 Gradle 7.x 使用 Version Catalogs 管理依赖

一、根目录下 build.gradle 变更

变更前:

buildscript {
    ext.kotlin_version = '1.5.0'

    repository {
    repository {
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"
        classpath "com.google.protobuf:protobuf-gradle-plugin:0.8.17"

        // 自定义 gradle 插件
        classpath "com.sharpcj.plugin:abc:1.0.6"
    }
}


allprojects {
    repositories {
        mavenCentral()
        jcenter()
        maven {
            url "http://xx.xx.xx.xx:xxxx/xx/xx/"
        }
    }    
}

变更后:

根目录下的 buildscript 变更到 settings.gradle 中

setting.gradle

pluginManagement {
    repositories {
        gradlePluginPortal()
        google()
        mavenCentral()
        maven {
            allowInsecureProtocol = true
            url "http://xx.xx.xx.xx:xxxx/xx/xx/"
        }
}
dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' }
        maven {
            allowInsecureProtocol = true
            url "http://xx.xx.xx.xx:xxxx/xx/xx/"
        }
    }
}

gradle 7.0.x 以上对于 http 协议的的仓库地址,需要显示声明:allowInsecureProtocol = true

根目录下 build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// 全局 buildescript 依旧可以用
buildscript {
    ext.kotlin_version = '1.5.0'

    // 自定义 gradle 插件
    dependencies {
        classpath "com.sharpcj.plugin:abc:1.0.6"
    }
}

plugins {
    id 'com.android.application' version '7.3.1' apply false
    id 'com.android.library' version '7.3.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
    id 'com.google.protobuf' version '0.8.17' apply false
}

二、引入 aar 包gradle

7.0.x 以前:

  1. 将aar文件复制到libs文件夹中

  2. 在 model 下 build.gradle 中的 android {} 外层添加:

repositories {
    flatDir {
        dirs 'libs'
    }
}
  1. 在 dependencies 中加入
implementation files('libs/xxx.jar')

或者:

implementation(fileTree("libs"));

7.0.x 以上:

  1. 将aar文件复制到libs文件夹中
  2. build.gradle的dependencies中加入:
implementation(fileTree("libs"));

三、Version Catalogs —— 全新的管理依赖方式

3.1 此前的 Android 统一依赖管理的方式

3.1.1 传统apply from的方式

为了对模块进行统一管理,会在根目录新建一个config.gradle文件或者在根目录的build.gradle定义一些变量

ext {
    // ...
}

模块下的 build.gradle 使用则通过 apply 方式引入。 添加

apply from "config.gradle"

3.1.2 buildSrc方式

什么是 buildSrc

当运行 Gradle 时会检查项目中是否存在一个名为 buildSrc 的目录。然后 Gradle 会自动编译并测试这段代码,并将其放入构建脚本的类路径中, 对于多项目构建,只能有一个 buildSrc 目录,该目录必须位于根项目目录中, buildSrc 是 Gradle 项目根目录下的一个目录,它可以包含我们的构建逻辑,与脚本插件相比,buildSrc 应该是首选,因为它更易于维护、重构和测试代码

特点

共享 buildSrc 库工件的引用,全局只有一个地方可以修改它。

优点

支持自动补全,支持跳转。

缺点

依赖更新将重新构建整个项目。

3.1.3 Composing builds

什么是Composing builds

复合构建只是包含其他构建的构建. 在许多方面,复合构建类似于 Gradle 多项目构建,不同之处在于,它包括完整的 builds ,而不是包含单个 projects。

特点

拥有buildSrc的优点,同时依赖更新不用重新构建整个项目

3.2 Verison Catalogs 管理

3.2.1 Version Catalogs 特点

  • 对所有module可见,可统一管理所有module的依赖,Gradle会为每个依赖目录生成一个类型安全的访问器,如:libs.coreKtx。 每个依赖目录对构建项目都是可见的,确保依赖项的版本适用于每个子项目或模块
  • 依赖项除了可以声明为单个依赖目录,还可以将多个依赖项声明为依赖目录组。即支持声明依赖bundles, 即总是一起使用的依赖可以组合在一起,
  • 支持版本号与依赖名分离,可以在多个依赖间共享版本号
  • 支持在单独的libs.versions.toml文件中配置依赖
  • 支持在项目间共享依赖

3.2.2 启用 version Catalogs

由于此前 Version Catalogs 属于孵化中的特效,使用它之前需要启用该特性。
在 settings.gradle 中添加如下代码:

settings.gradle

pluginManagement {
	 ...
}

// VERSION_CATALOGS当前并不是稳定版本功能
// 所以需要预先开启功能预览 enableFeaturePreview('FEATURE')
enableFeaturePreview("VERSION_CATALOGS")

dependencyResolutionManagement {
	...
}

但是当我使用 gradle 8.0 的时候,我发现该特性已经是稳定版本了,直接使用即可。无需再启用。在网上看到有说是从 gradle-7.4.1-src 版本开始转为正式版的。有待考证。实际使用的时候,如果编译报错提示了就加上。

3.2.3 使用 version catalog

声明 version catalogs

一种方式是直接在 Settings.gradle 中声明,如下:

settings.gradle

dependencyResolutionManagement {
    
		......

    // 编写版本目录的依赖库
    versionCatalogs {
        libs {
            // 分别声明依赖别名('coreKtx'),groupId('androidx.core'),artifactId('core-ktx')以及版本('1.7.0')
            alias('coreKtx').to('androidx.core', 'core-ktx').version('1.7.0')
            alias('appcompat').to('androidx.appcompat', 'appcompat').version('1.3.0')
            alias('material').to('com.google.android.material', 'material').version('1.4.0')
            alias('constraintlayout').to('androidx.constraintlayout', 'constraintlayout').version('2.0.4')
            alias('junit-junit').to('junit', 'junit').version('4.13.2')
            alias('junit-ext').to('androidx.test.ext', 'junit').version('1.1.3')
            alias('junit-espresso').to('androidx.test.espresso', 'espresso-core').version('3.4.0')
        
        
            // 针对对个相同版本号的依赖,我们可以定一个通用版本号,即将依赖与版本单独声明并引用
            version('lifecycle', '2.2.0')
            alias('lifecycleExtensions').to('androidx.lifecycle', 'lifecycle-extensions').versionRef('lifecycle')
            alias('lifecycleRuntime').to('androidx.lifecycle', 'lifecycle-runtime-ktx').versionRef('lifecycle')

			// 除了单个依赖声明,我们也可以将多个依赖项声明为一个依赖组
            bundle('appBaseLib', ['coreKtx', 'appcompat', 'material', 'constraintlayout'])

            // 声明一个插件
             alias('kotlin-kapt').toPluginId('org.jetbrains.kotlin.kapt').version("1.7.0")
             alias('kotlin-parcelize').toPluginId('org.jetbrains.kotlin.plugin.parcelize').version("1.7.0")
				}
    }
}

使用 version catalogs

plugins {
	......

    // 使用版本目录中声明的插件
    alias libs.plugins.kotlin.kapt
    alias libs.plugins.kotlin.parcelize
}

......

dependencies {
    // 依赖单个制定的版本目录
    implementation libs.coreKtx
    implementation libs.appcompat
    implementation libs.material
    implementation libs.constraintlayout

    implementation libs.lifecycleExtensions
    implementation libs.lifecycleRuntime

    testImplementation libs.junit.junit
    androidTestImplementation libs.junit.ext
    androidTestImplementation libs.junit.espresso

    // 依赖版本目录组
    // implementation libs.bundles.appBaseLib
}

通过 TOML 文件声明 version catalogs

除了在 settings.gradle 文件中直接声明依赖目录,官方更推荐使用 TOML 文件来声明依赖目录

首先在项目根目录下创建 libs.versions.toml 文件,文件名可以任意取,并编写如下依赖内容:

[versions]
kotlin = "1.7.0"
appcompat = "1.3.0"
material = "1.4.0"
constraintlayout = "2.0.4"
lifecycle = "2.2.0"

[libraries]
coreKtx = { module = "androidx.core:core-ktx", version.ref = "kotlin" }
appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" }
material = { module = "com.google.android.material:material", version.ref = "material" }
constraintlayout = { module = "androidx.constraintlayout:constraintlayout", version.ref = "constraintlayout" }
lifecycleExtensions = { module = "androidx.lifecycle:lifecycle-extensions", version.ref = "lifecycle" }
lifecycleRuntime = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle" }
junit-junit = { module = "junit:junit", version = "4.13.2" }
junit_ext = { module = "androidx.test.ext:junit", version = "1.1.3" }
junit_espresso = { module = "androidx.test.espresso:espresso-core", version = "3.4.0" }

[bundles]
appBaseLib = ["coreKtx", "appcompat", "material", "constraintlayout"]

[plugins]
kotlin-kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlin" }
kotlin-parcelize = { id = "org.jetbrains.kotlin.plugin.parcelize", version.ref = "kotlin" }

随后在 setting.gradle 中引用该 TOML 文件

settings.gradle

dependencyResolutionManagement {
    
    ......


    // 第二种方式使用版本目录
    libs {
        from(files("./libs.versions.toml"))
    }
}

然后在app build.gradle 中使用 TOML 文件中声明的依赖

......

dependencies {

    implementation libs.bundles.appBaseLib

    implementation libs.lifecycleExtensions
    implementation libs.lifecycleRuntime

    testImplementation libs.junit.junit
    androidTestImplementation libs.junit.ext
    androidTestImplementation libs.junit.espresso
}

TOML 文件的使用说明

  1. TOML 文件由4个主要部分组成
    [versions] 用于声明可以被依赖项引用的版本
    [libraries] 用于声明依赖的别名
    [bundles] 用于声明依赖包(依赖组)
    [plugins] 用于声明插件

不可随意自定义 TOML 文件中的节点,否则会报错提示只能使用 versionslibrariesbundlespluginsmetadata 中的一个。关于 metadata 的作用暂且不清楚,查阅 gradle 官方文档也只提到前四个。

  1. 在使用 TOML 文件时,默认名是 libs, 如果创建的文件放置于 project/gradle/ 目录下面,则在 settings.gradle 文件中可以省略声明。建议显示声明。

  2. 声明 libraries 时,可以使用

coreKtx = { module = "androidx.core:core-ktx", version.ref = "kotlin" }

或者

coreKtx = { group = "androidx.core", name = "core-ktx", version.ref = "kotlin" }

  1. TOML 文件中变量命名大小写敏感,且以小写字母开头, 命名中可以如包含 - 或者 _或者. ,在相当于分组了。举例说明:
coreKtx = { module = "androidx.core:core-ktx", version.ref = "kotlin" }
lifecycle_runtime = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle"}
lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "lifecycle"}

在使用时分别为:

implementation libs.coreKtx
implementation libs.lifecycle.runtime
implementation libs.lifecycle.viewmodel
  1. 最后 TOML 还可以发布到远程仓库

四、参考资料

【Gradle7.0】依赖统一管理的全新方式,了解一下~

Version Catalog(中央依赖声明,即:版本目录)

Android 官方建议迁移至 Version Catalogs

Version Catalogs Gradle 官方页面

posted @ 2023-05-13 19:17  SharpCJ  阅读(5182)  评论(0编辑  收藏  举报