没有配置 nexus 之前,如果本地仓库没有,去中央仓库下载,通常在企业中会在局域网内部署一台私服服务器,有了私服本地项目首先去本地仓库找 jar,如果没有找到则连接私服从私服下载 jar 包,如果私服没有 jar 包私服同时作为代理服务器从中央仓库下载 jar 包,这样做的好处是一方面由私服对公司项目的依赖 jar 包统一管理,一方面提高下载速度,项目连接私服下载 jar 包的速度要比项目连接中央仓库的速度快的多。
nexus中包括很多仓库,hosted中存放的是企业自己发布的jar包及第三方公司的jar包,proxy 中存放的是中央仓库的 jar,为了方便从私服下载 jar 包可以将多个仓库组成一个仓库组,每个工程需要连接私服的仓库组下载 jar 包。
打开 nexus 配置仓库组,如下图:
上图中仓库组包括了本地仓库、代理仓库等。
在客户端的 setting.xml 中配置私服的仓库,由于 setting.xml 中没有 repositories 的配置标签需要使用 profile 定义仓库。
<profile>
<!--profile 的 id-->
<id>dev</id>
<repositories>
<repository>
<!--仓库 id,repositories 可以配置多个仓库,保证 id 不重复-->
<id>nexus</id>
<!--仓库地址,即 nexus 仓库组的地址-->
<url>http://localhost:8081/nexus/content/groups/public/</url>
<!--是否下载 releases 构件-->
<releases>
<enabled>true</enabled>
</releases>
<!--是否下载 snapshots 构件-->
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<!-- 插件仓库,maven 的运行依赖插件,也需要从私服下载插件 -->
<pluginRepository>
<!-- 插件仓库的 id 不允许重复,如果重复后边配置会覆盖前边 -->
<id>public</id>
<name>Public Repositories</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
</pluginRepository>
</pluginRepositories>
</profile>
使用 profile 定义仓库需要激活才可生效。
<activeProfiles>
<activeProfile>dev</activeProfile>
</activeProfiles>
配置成功后通过 eclipse 查看有效 pom,有效 pom 是 maven 软件最终使用的 pom 内容,程序员不直接编辑有效 pom,打开有效 pom
有效 pom 内容如下: 下边的 pom 内容中有两个仓库地址,maven 会先从前边的仓库的找,如果找不到 jar 包再从下边的找,从而就实现了从私服下载 jar 包。
<repositories>
<repository>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
<id>public</id>
<name>Public Repositories</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
</repository>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>Public Repositories</name>
<url>http://localhost:8081/nexus/content/groups/public/</url>
</pluginRepository>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
测试 1:局域网环境或本地网络即可 在 ssm_service 工程中添加以上配置后,添加 ssm_dao 工程的依赖,删除本地仓库中 ssm_dao工程,同时在 eclipse 中关闭 ssm_dao 工程。观察控制台:
项目先从本地仓库找 ssm_dao,找不到从私服找,由于之前执行 deploy 将 ssm_dao 部署到私服中,所以成功从私服下载 ssm_dao 并在本地仓库保存一份。如果此时删除私服中的 ssm_dao,执行 update project 之后是否正常?如果将本地仓库的 ssm_dao 和私服的 ssm_dao 全部删除是否正常?
在项目的 pom.xml 添加一个依赖,此依赖在本地仓库和私服都不存在,maven 会先从本地仓库找,本地仓库没有再从私服找,私服没有再去中央仓库下载,jar 包下载成功在私服、本地仓库分别存储一份。