Maven-组织内部项目统一配置DistributionManagement

搜了一下中文技术博客上似乎没有相关的文章,就简要翻译一下。

需求

假设公司内部有非常多Maven项目,需要deploy到一个内部maven私有仓库中。
如果希望maven deploy命令可以成功执行,一般需要在pom.xml中添加:

1
2
3
4
5
6
<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>

但需要deploy的项目很多的情况下,我们肯定不希望在每个项目的pom文件中都重复添加这个配置。

方案一

为所有项目增加一个公共的parent pom项目。那么只需要在这个项目的pom文件中添加:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>

<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>

</project>

然后使其他项目的parent项目变成这个项目:

1
2
3
4
5
<parent>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0</version>
</parent>

方案二

方案一存在两个问题:

  • 如果代码泄露或将代码开源,会使该内部私有仓库的地址被暴露
  • 私有仓库这种环境配置信息最好和代码分离。类似通过配置中心,将数据库地址等配置和代码分离。

我们完全可以将这个配置放到maven中。
可以通过mvn命令的启动参数来实现:

1
2
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

更好的方法是将其配在settings.xml中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>

<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>

</settings>

不要忘记也在<server></server>之间加上snapshotsreleases的账号。

参考资料

java - How to specify maven’s distributionManagement organisation wide? - Stack Overflow

本文永久链接 [ https://galaxyyao.github.io/2019/09/18/Maven-组织内部项目统一配置DistributionManagement/ ]