新版Gradle中如何以libs格式编写Retrofit依赖?
新版Gradle添加Retrofit依赖的正确方式
方式一:直接声明依赖(无需版本目录)
这是最直接的写法,适用于不想配置版本目录的场景:
- 若使用Groovy语法(
build.gradle):
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
- 若使用Kotlin DSL语法(
build.gradle.kts):
implementation("com.squareup.retrofit2:retrofit:2.9.0")
方式二:使用Gradle版本目录(libs.versions.toml)
如果想用libs.xxx的写法,需要先完成版本目录配置:
- 在项目根目录的
gradle/libs.versions.toml文件中添加配置:
[versions] retrofit = "2.9.0" [libraries] com-squareup-retrofit2-retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
- 在模块的构建文件中引用:
- Groovy语法(
build.gradle):
implementation libs.com.squareup.retrofit2.retrofit
- Kotlin DSL语法(
build.gradle.kts):
implementation(libs.com.squareup.retrofit2.retrofit)
错误写法说明
你之前尝试的implementation(libs.com.squareup.retrofit2:retrofit:2.9.0)是错误的,因为版本目录的引用方式是调用预配置的libs对象属性,不能直接在括号内使用带版本号的完整依赖路径。
内容的提问来源于stack exchange,提问作者Harshvardhan Singh Negi
相关产品推荐
相关产品推荐

