在POM中为Maven配置仓库和插件仓库。例如当需要为项目添加Nexus私服上的public仓库时,可以按如下配置:
<project>
...
<repositories>
<repository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
...
</project>
这样的配置只对当前Maven项目有效,在实际应用中,我们往往想要通过一次配置就能让本机所有的Maven项目都使用自己的Maven私服。这个时候就会想到settings.xml文件,该文件中的配置对所有本机Maven项目有效,但是settings.xml并不支持直接配置repositories和pluginRepositories。索性Maven还提供了Profile机制,能让用户将仓库配置放到settings.xml中的proile中,如下:
<settings>
...
<profiles>
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
...
</settings>
该配置中使用了一个id为nexus的profile,这个profile包含了相关的仓库配置,同时配置中又使用activeProfile元素将nexus这个profile激活,这样当执行Maven构建的时候,激活的profile会将仓库配置应用到项目中去。上面的配置已经能让本地所有的Maven项目从Nexus私服下载构件,但是有时还会不时地访问中央仓库central,我们希望的是所有maven下载请求都仅仅通过Nexus以全面发挥私服的作用。这个时候就需要借助Maven镜像配置了。可以创建一个匹配任何仓库的镜像,镜像的地址为私服,这样Maven对任何仓库的构件下载请求都会转到私服中。具体配置如下:
<settings>
...
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://localhost:8081/nexus/content/groups/public/</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>nexus</id>
<name>Nexus</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
...
</settings>
仓库及插件仓库配置的 id 都是 central,他们覆盖了超级 POM 中央仓库的配置,它们的 url 已经无关紧要,因为所有的请求都会通过镜像访问私服地址。配置仓库及插件仓库的主要目的是开启对快照版本下载的支持,当 Maven 需要下载发布版或快照版构件的时候,它首先检查 central,看该类型的构件是否支持,得到正面的回答之后,再根据镜像匹配规则转而访问私服仓库地址。
本文介绍如何在Maven项目中配置Nexus私服,并通过settings.xml文件全局设置仓库和插件仓库,利用Profile机制实现灵活配置。此外,还介绍了如何通过镜像配置确保所有依赖下载请求都通过私服完成。
530

被折叠的 条评论
为什么被折叠?



