小编典典

Java Maven:按相对路径向jar添加依赖项

java

我有一个专有的jar,要作为依赖项添加到pom中。

但是我不想将其添加到存储库中。原因是我希望我通常的Maven命令(例如)可以mvn compile直接使用。(无需开发人员自己将其添加到某个存储库中)。

我希望该jar位于源代码管理的3rdparty库中,并通过pom.xml文件中的相对路径链接到它。

能做到吗?怎么样?


阅读 1306

收藏
2020-02-26

共1个答案

小编典典

我希望该jar位于源代码管理的3rdparty库中,并通过pom.xml文件中的相对路径链接到它。

如果你真的想这个(明白,如果你不能使用公司资源库),那么我的建议是使用“文件库”本地的项目,并没有使用一个system范围依赖。system应该避免使用作用域,这样的依赖项在许多情况下(例如在组装中)不能很好地工作,它们带来的麻烦多于收益。

因此,改为声明项目本地的存储库:

<repositories>
  <repository>
    <id>my-local-repo</id>
    <url>file://${basedir}/my-repo</url>
  </repository>
</repositories>

使用中有你安装第三方的lib install:install-filelocalRepositoryPath参数:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

更新:在使用插件的2.2版时,它似乎install:install-file忽略了localRepositoryPath。但是,它可与2.3版及更高版本的插件一起使用。因此,请使用插件的标准名称来指定版本:

mvn org.apache.maven.plugins:maven-install-plugin:2.3.1:install-file \
                         -Dfile=<path-to-file> -DgroupId=<myGroup> \ 
                         -DartifactId=<myArtifactId> -Dversion=<myVersion> \
                         -Dpackaging=<myPackaging> -DlocalRepositoryPath=<path>

maven-install-plugin文档

最后,像其他任何依赖项一样声明它(但不包含system范围):

<dependency>
  <groupId>your.group.id</groupId>
  <artifactId>3rdparty</artifactId>
  <version>X.Y.Z</version>
</dependency>

恕我直言,这是比使用system范围更好的解决方案,因为你的依赖项将被视为好公民(例如,它将包含在程序集中等等)。

现在,我不得不提到在公司环境中处理这种情况的“正确方法”(这里可能不是这种情况)将是使用公司存储库。

2020-02-26