在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>