解决 Gradle 报错 Could not resolve all artifacts for configuration
分析 Gradle 构建时报 Could not resolve all artifacts 诱因,详解 maven 镜像源配置、证书异常与本地缓存清理。
问题现象
在进行 Spring Boot 或 Android 项目编译、执行 ./gradlew build 时,构建失败:
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:compileJava'.
> Could not resolve all artifacts for configuration ':app:compileClasspath'.
> Could not find com.example:common-utils:1.2.0.
Required by:
project :app
> Could not resolve org.springframework.boot:spring-boot-starter-web:3.1.2.
> Could not get resource 'https://repo.maven.apache.org/maven2/...'.
> Connect to repo.maven.apache.org:443 failed: Connection timed out
依赖包下载受阻,整个构建流程直接中断。
触发根因
- 远程仓库连接超时或被屏蔽:项目配置了官方
mavenCentral()或google()仓库,国内构建机在拉取海外 Maven 节点时发生 TCP 超时或丢包。 - 私有仓库凭证缺失或配置错位:依赖的库属于团队内部私服(Nexus/Artifactory),在
build.gradle中声明了私服地址,但未在gradle.properties中注入对应的认证用户名密码。 - 本地 Gradle 依赖缓存元数据损坏:之前的下载过程被强制按 Ctrl+C 中断,
~/.gradle/caches/目录留下了不完整的锁定文件与损坏的.pom描述。
诊断排查步骤
1. 使用带堆栈与详细调试信息的命令定位失败的 URL
./gradlew build --stacktrace --info
日志中会明确指出 Gradle 尝试从哪几个 URL 下载该 jar 包以及每个 URL 返回的具体 HTTP 状态码(如 401 Unauthorized、403 Forbidden 还是 Connection Refused)。
解决方案
方案一:在 build.gradle 中配置国内高效镜像仓库(解决网络阻断)
在根目录 settings.gradle(Gradle 7+)或 build.gradle 中,将阿里云/腾讯云镜像源置于最顶层:
// settings.gradle (推荐 Gradle 7+ 语法)
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)
repositories {
maven { url 'https://maven.aliyun.com/repository/public' }
maven { url 'https://maven.aliyun.com/repository/google' }
mavenCentral()
google()
}
}
方案二:配置私有仓库认证(~/.gradle/gradle.properties)
避免将敏感凭据硬编码在代码库中:
在用户主目录下配置 ~/.gradle/gradle.properties:
nexusUsername=my_username
nexusPassword=my_secret_token
在 build.gradle 中引用:
repositories {
maven {
url = uri("https://nexus.company.com/repository/maven-releases/")
credentials {
username = project.findProperty("nexusUsername") ?: ""
password = project.findProperty("nexusPassword") ?: ""
}
}
}
方案三:清理 Gradle 本地缓存并强制刷新依赖
强制清除并重新拉取依赖:
# 1. 强制让 Gradle 刷新所有快照与依赖缓存
./gradlew build --refresh-dependencies
# 2. 如果依然报错,清理损坏的本地模块缓存
rm -rf ~/.gradle/caches/modules-2/
验证方法
再次执行构建:
./gradlew compileJava
输出显示:
> Task :app:compileJava UP-TO-DATE
BUILD SUCCESSFUL in 4s
全部所需 jar 包顺利下载并解析完毕,依赖问题根除。


