章
目
录
在Maven的使用过程中,大家可能会碰到这样的困扰:明明在pom.xml
文件里配置了仓库,可就是不生效。今天这篇文章,就专门来给大家讲讲这个问题,并且分享有效的解决办法。
一、问题描述
在Maven环境下进行项目构建时,我们常常需要配置依赖库的仓库地址。通常,我们会在pom.xml
文件里进行相关配置。比如下面这段配置代码:
<repositories>
<repository>
<id>libs-snapshot</id>
<name>libs-release</name>
<url>仓库地址</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>libs-release</id>
<name>libs-release</name>
<url>仓库地址</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
这段代码的作用是配置了两个仓库,一个是用于快照版本(libs-snapshot
)的仓库,另一个是用于发布版本(libs-release
)的仓库 。配置完后,我们期望Maven能从这些指定的仓库中获取依赖。但实际情况却可能不尽如人意,配置好像没起作用。
与此同时,我们还需要知道,settings.xml
文件在Maven中也起着重要作用。它里面的mirrors
配置项,可以指定仓库的镜像地址。比如下面这样的配置:
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://192.168.69.166:8081/repository/maven-public/</url>
</mirror>
</mirrors>
这段代码表示配置了一个名为nexus
的镜像,mirrorOf
的值为*
,意味着它会替代所有仓库的请求,Maven会从指定的http://192.168.69.166:8081/repository/maven-public/
这个地址去获取依赖。这就可能导致我们在pom.xml
里配置的仓库被覆盖,从而出现不生效的情况。
二、解决办法
想要让pom.xml
里配置的repositories
生效,我们可以对settings.xml
里的mirrors
配置进行调整。修改后的配置如下:
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository. The repository that
| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
<mirror>
<id>nexus</id>
<mirrorOf>*,!libs-snapshot,!libs-release</mirrorOf>
<url>http://192.168.69.166:8081/repository/maven-public/</url>
</mirror>
</mirrors>
在这个配置中,mirrorOf
的值变为了*,!libs-snapshot,!libs-release
。这里的!
表示排除的意思,也就是说,除了libs-snapshot
和libs-release
这两个仓库,其他仓库的请求还是会走nexus
这个镜像地址,而libs-snapshot
和libs-release
则会按照pom.xml
里配置的仓库地址去获取依赖,这样就保证了pom.xml
里配置的这两个仓库能够生效。
三、总结
在Maven开发中,配置仓库既可以在pom.xml
文件里进行,也可以在settings.xml
文件里完成。具体选择哪种方式,主要取决于个人的习惯以及项目的实际需求。希望通过本文的介绍,大家以后再遇到pom.xml
中repositories
不生效的问题,能够轻松解决。