在maven->settings.xml中配置多个mirror镜像,镜像只会执行第一个位置mirror
。
- 有这样一个问题:一台笔记本,在公司用部门搭建的maven私服,回到家用aliyun的镜像,每次都要改配置文件,如果能在
不改动配置文件的情况下,动态切换mirror配置
,那就very nice了。 - 于是乎想到了settings.xml可以使用变量,我们可以试图使用变量来解决这个问题。
首先来看下mirror结点的结构吧
<!-- 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>
-->
<!-- 唯一标识一个mirror -->
<id>mirrorId</id>
<!-- 代表这个镜像的替代位置,例如central就表示替代官方的中央仓库。我们可以将这个地方设置为变量,然后通过手动指定变量地方式动态切换mirror -->
<!-- mirrorOf指定这个镜像是针对哪个repository的,配置成*就表示要代理所有repository的请求 -->
<mirrorOf>repositoryId</mirrorOf>
<!-- 名字(个人感觉这个name作用主要是给自己识别用,因为id已经在当前xml中唯一指定了一个mirror) -->
<name>Human Readable Name for this Mirror.</name>
<!-- 官方仓库库的地址 -->
<url>http://my.repository.com/repo/path</url>
</mirror>
- 把配置文件配置为这样:
为了简单,我这里直接把mirrorOf设置为central中央库
<mirrors>
<mirror>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>${aliyun}</mirrorOf>
</mirror>
<mirror>
<id>netease</id>
<url>http://mirrors.163.com/maven/repository/maven-public/</url>
<mirrorOf>${netease}</mirrorOf>
</mirror>
<mirror>
<id>default</id>
<url>center URL</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
配置多个mirror的情况下,默认只有第一个生效。因此我们可以把最后一个作为默认值,前面配置的使用环境变量动态切换。
默认执行: mvn help:effective-settings
可以看到使用的是最后一个
切换阿里镜像执行mvn help:effective-settings -Daliyun=central
即可
同理,切换网易mvn help:effective-settings -Dnetease=central
mvn help:effective-settings -D你的mirrorId=central
- 附上几个仓库mirror
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
<mirror>
<id>ui</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://uk.maven.org/maven2/</url>
</mirror>
<mirror>
<id>ibiblio</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2/</url>
</mirror>
<mirror>
<id>jboss-public-repository-group</id>
<mirrorOf>central</mirrorOf>
<name>JBoss Public Repository Group</name>
<url>http://repository.jboss.org/nexus/content/groups/public</url>
</mirror>
<mirror>
<id>OSCN</id>
<name>OSChina Central</name>
<url>http://maven.oschina.net/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>