且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Maven:通过相对路径将依赖项添加到 jar

更新时间:2023-09-30 10:27:34

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

I want the jar to be in a 3rdparty lib in source control, and link to it by relative path from the pom.xml file.

如果您真的想要这个(请理解,如果您不能使用公司存储库),那么我的建议是使用项目本地的文件存储库"并且不使用system 范围依赖.应该避免 system 作用域,这种依赖在许多情况下(例如在汇编中)不能很好地工作,它们带来的麻烦多于好处.

If you really want this (understand, if you can't use a corporate repository), then my advice would be to use a "file repository" local to the project and to not use a system scoped dependency. The system scoped should be avoided, such dependencies don't work well in many situation (e.g. in assembly), they cause more troubles than benefits.

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

So, instead, declare a repository local to the project:

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

使用 install:install-filelocalRepositoryPath 参数:

Install your third party lib in there using install:install-file with the localRepositoryPath parameter:

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 及更高版本的插件.所以使用插件的全限定名来指定版本:

Update: It appears that install:install-file ignores the localRepositoryPath when using the version 2.2 of the plugin. However, it works with version 2.3 and later of the plugin. So use the fully qualified name of the plugin to specify the version:

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-插件文档

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

Finally, declare it like any other dependency (but without the system scope):

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

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

This is IMHO a better solution than using a system scope as your dependency will be treated like a good citizen (e.g. it will be included in an assembly and so on).

现在,我不得不提一下,在公司环境中处理这种情况的正确方法"(可能不是这里的情况)是使用公司存储库.

Now, I have to mention that the "right way" to deal with this situation in a corporate environment (maybe not the case here) would be to use a corporate repository.