原文地址: https://lcy362.github.io/posts/32793/
maven里的mirror和repository是兩個比較容易混淆的概念,它們的作用都是配置遠程maven倉庫的地址。顧名思義,repository就是直接配置站點地址,mirror則是作為站點的鏡像,代理某個或某幾個站點的請求,實現對repository的完全代替。
repository
有兩種形式可以配置多個repository, 配置多個profile或者在同一個profile中配置多個repository.配置多profile時,還需要配置activeProfiles使配置生效。
配置示例:
<profiles>
</profile>
<profile>
<id>central</id>
<repositories>
<repository>
<id>central</id>
<url>http://search.maven.org/</url>
<!-- <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled>
</snapshots> -->
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://search.maven.org/</url>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
<profile>
<id>aliyun</id>
<repositories>
<repository>
<id>aliyun</id>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<!-- <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled>
</snapshots> -->
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun</id>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>aliyun</activeProfile>
<activeProfile>central</activeProfile>
</activeProfiles>
單profile,多repository的配置也類似。
這樣就實現了多站點的配置。下載依賴時,maven會按照配置從上到下的順序,依次嘗試從各個地址下載,成功下載為止。
mirror
個人感覺mirror的存在有些雞肋,如果不想用repository里配的地址,完全可以直接改掉,而不用再加一條mirror配置。
如果setting.xml和pom里都配置了repository, 配置的mirror是可以對兩個配置文件都生效的,這可能是mirror存在的唯一意義。
mirror的配置示例:
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
使用mirrorOf指定這個鏡像是針對哪個repository的,配置成*就表示要代理所有repository的請求。
需要注意的是,與repository不同,配置到同一個repository的多個mirror時,相互之間是備份的關系,只有在倉庫連不上的時候才會切換另一個,而如果在能連上的情況下找不到包,是不會嘗試下一個地址的。
所以,一般情況下,無論是配置國內的maven倉庫,還是配置nexus之類私服,都可以直接配置成repository, 這樣即使配置的這些倉庫有些問題導致一些包下不下來,也可以繼續用別的倉庫嘗試。
