Maven 中的「库」其实有两种完全不同的概念,很多人混淆,导致配置出错。下面用最清晰的方式给你彻底讲清楚:
一、两种“库”(Repository)的区别(99%的人都搞混过)
| 名称 | 英文全称 | 作用 | 配置位置(pom.xml 中) | 谁来用它? |
|---|---|---|---|---|
| 本地库(本地仓库) | Local Repository | 你电脑上缓存的所有 jar 包的文件夹 | 不需要配置(默认在 ~/.m2/repository) | 只有你本机 Maven 使用 |
| 远程库(远程仓库) | Remote Repository | 网络上的 jar 包仓库(别人上传的) | 和 | Maven 去下载依赖和插件 |
一句话总结:
- 本地库 = 你家硬盘上的 jar 缓存仓库(只有一个)
- 远程库 = 互联网上的 jar 超市(可以有无数个)
二、最常用的远程库(直接抄就行)
<project>
<repositories>
<repository>
<id>central</id>
<name>Maven Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</repository>
<!-- 阿里云镜像(国内最快!强烈推荐) -->
<repository>
<id>aliyun</id>
<name>Aliyun Maven Repository</name>
<url>https://maven.aliyun.com/repository/public</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
<!-- 华为云镜像(也很稳) -->
<repository>
<id>huaweicloud</id>
<name>HuaweiCloud Maven Repository</name>
<url>https://repo.huaweicloud.com/repository/maven/</url>
</repository>
</repositories>
<!-- 插件也需要远程库(大多数人忘了配这个) -->
<pluginRepositories>
<pluginRepository>
<id>aliyun-plugin</id>
<url>https://maven.aliyun.com/repository/public</url>
</pluginRepository>
</pluginRepositories>
</project>
三、最佳实践:直接改 settings.xml(全局生效,一劳永逸)
路径:~/.m2/settings.xml(没有就新建一个)
<settings>
<mirrors>
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf> <!-- * 表示拦截所有远程仓库请求 -->
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
</mirrors>
<!-- 可选:加快插件下载 -->
<pluginRepositories>
<pluginRepository>
<id>aliyun-plugin</id>
<url>https://maven.aliyun.com/repository/public</url>
</pluginRepository>
</pluginRepositories>
</settings>
配好这个后,全国所有 Maven 项目下载速度直接起飞,再也不用看红色的下载失败!
四、常见的远程仓库地址大全(收藏)
| 仓库名称 | 地址 | 特点 |
|---|---|---|
| Maven 中央仓库 | https://repo.maven.apache.org/maven2 | 官方、最全,但国内慢 |
| 阿里云镜像 | https://maven.aliyun.com/repository/public | 国内最快、最全、强烈推荐 |
| 华为云镜像 | https://repo.huaweicloud.com/repository/maven/ | 也很稳 |
| 腾讯云镜像 | https://mirrors.cloud.tencent.com/nexus/repository/maven-public/ | 不错 |
| Sonatype Nexus | https://oss.sonatype.org/content/repositories/releases | 很多新 jar 先在这里发布 |
| Spring 官方仓库 | https://repo.spring.io/release | Spring 全家桶 |
| JBang 仓库 | https://repo1.maven.org/maven2 | 备用中央仓库 |
五、常见问题解决
| 问题 | 解决办法 |
|---|---|
| 下载依赖一直卡在 0% | 改用阿里云镜像(settings.xml) |
| 某些 jar 中央仓库没有 | 加 Sonatype 或公司私服 |
| 公司内部私服(Nexus/Artifactory) | 在 pom.xml 或 settings.xml 中加 |
| 插件下载失败 | 一定要配 |
六、一张图记住 Maven 仓库工作流程
你的代码 (pom.xml)
↓ 依赖不存在
本地仓库 ~/.m2/repository → 不存在 → 去 settings.xml 的 mirrors 列表
↑ 存在,直接使用 ↓
阿里云/华为云/中央仓库
↓
下载 jar → 缓存到本地仓库
记住了:本地库是缓存,远程库才是源头,阿里云是加速器。
把上面阿里云的 settings.xml 配置复制过去,你这辈子都不用再为 Maven 下载慢而烦恼了!