settings.xml 是 Maven 的全局配置文件,用于配置仓库镜像、私有仓库、认证凭据等;优先加载用户级 ${user.home}/.m2/settings.xml;常用场景包括通过 mirrors 配置阿里云镜像、用 profiles 启用 Nexus 私服、在 servers 中配认证信息且 id 必须一致。

settings.xml 是 Maven 的配置文件,用于控制构建行为、仓库地址、认证凭据、代理等。它不定义项目本身(那是 pom.xml 的职责),而是影响所有使用该 Maven 实例的项目——换句话说,它是“全局”或“用户级”的行为开关。
settings.xml 的位置和优先级
Maven 会按顺序加载两个 settings.xml 文件,后加载的覆盖前一个的同名配置:
- 全局配置:
${maven.home}/conf/settings.xml(对所有用户生效,需管理员权限修改) - 用户配置:
${user.home}/.m2/settings.xml(推荐使用,无需权限,且不会被 Maven 升级覆盖)
绝大多数场景下,你应该只编辑用户级的 ${user.home}/.m2/settings.xml。如果该文件不存在,可手动创建,或从 ${maven.home}/conf/settings.xml 复制一份作为起点。
用 mirrors 配置国内镜像仓库(最常用场景)
默认中央仓库(https://repo.maven.apache.org/maven2/)在国内访问慢且不稳定。通过 <mirrors> 节点可将所有对中央仓库的请求重定向到镜像源,比如阿里云 Maven 仓库。
在 settings.xml 的 <mirrors> 标签下添加:
<mirror> <id>aliyunmaven</id> <mirrorOf>central</mirrorOf> <name>Aliyun Maven</name> <url>https://maven.aliyun.com/repository/public</url> </mirror>
注意关键点:
-
<mirrorOf>central</mirrorOf>表示该镜像仅替换 ID 为central的仓库(即默认中央仓库) - 不要写成
<mirrorOf>*</mirrorOf>,否则可能意外拦截私有仓库或插件仓库 - 多个
<mirror>时,Maven 只取第一个匹配项,顺序很重要
用 profiles + activeProfiles 启用自定义仓库(如 Nexus 私服)
如果你公司内部部署了 Nexus 或 Artifactory,需要显式声明并启用它,不能靠 mirrors 简单覆盖(因为私服通常不是 central 的镜像,而是独立坐标空间)。
在 settings.xml 的 <profiles> 中添加:
<profile>
<id>nexus-repo</id>
<repositories>
<repository>
<id>nexus</id>
<url>https://nexus.example.com/repository/maven-public/</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
</profile>
再在 <activeProfiles> 中启用它:
<activeProfiles> <activeProfile>nexus-repo</activeProfile> </activeProfiles>
这样 Maven 就会在依赖解析时同时查询中央仓库(已被镜像)和你的私有 nexus 仓库。注意:<repository> 中的 <id> 必须与后续可能配置的 <servers> 凭据 ID 对应。
配置认证和服务器信息(访问私有仓库必需)
若私有仓库需要账号密码(如 Nexus 的 deployment 用户),必须在 <servers> 节点中配置,且 <id> 必须与 <repository> 或 <distributionManagement> 中的 id 完全一致:
<server> <id>nexus</id> <username>deploy-user</username> <password>xxx</password> </server>
⚠️ 重要提醒:不要明文写密码。生产环境应使用 Maven 的 settings-security.xml 加密密码,或改用 token(如 Nexus 支持 API Key)。另外,<server> 只作用于发布(mvn deploy)或拉取需认证的 snapshot 依赖,普通 public 仓库不需要此项。
真正容易出问题的地方往往不在语法,而在于:镜像配置错用了 mirrorOf 值导致私服失效;profile 写了但没 active;或者 server.id 和 repository.id 拼写不一致——Maven 不报错,只是静默跳过认证,最终提示 401 或找不到依赖。


















