You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新版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的写法,需要先完成版本目录配置:

  1. 在项目根目录的gradle/libs.versions.toml文件中添加配置:
[versions]
retrofit = "2.9.0"

[libraries]
com-squareup-retrofit2-retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
  1. 在模块的构建文件中引用:
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 23:42:05