如何将本地jar文件(还不是Maven存储库的一部分)直接添加到项目的库源中?


当前回答

真正快速而肮脏的方法是指向本地文件,请注意“system”现在已被弃用:

<dependency>
    <groupId>com.sample</groupId>  
    <artifactId>samplifact</artifactId>  
    <version>1.0</version> 
    <scope>system</scope>
    <systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>

然而,这只会存在于您的机器上(显然),因为共享通常使用适当的m2存档(nexus/artifactory)是有意义的,或者如果您没有这些存档或不想设置本地maven结构化存档并在pom中配置“存储库”:

本地:

<repositories>
    <repository>
        <id>my-local-repo</id>
        <url>file://C:/DEV//mymvnrepo</url>
    </repository>
</repositories>

远程:

<repositories>
    <repository>
        <id>my-remote-repo</id>
        <url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
    </repository>
</repositories>

对于此解决方案,还可以使用basedir变量创建相对路径:

<url>file:${basedir}</url>

其他回答

我想要这样的解决方案-在pom文件中使用maven安装插件:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    <executions>
        <execution>
            <phase>initialize</phase>
            <goals>
                <goal>install-file</goal>
            </goals>
            <configuration>
                <file>lib/yourJar.jar</file>
                <groupId>com.somegroup.id</groupId>
                <artifactId>artefact-id</artifactId>
                <version>x.y.z</version>
                <packaging>jar</packaging>
            </configuration>
        </execution>
    </executions>
</plugin>

在这种情况下,您可以执行mvn初始化,jar将安装在本地maven repo中。现在,这个jar可以在这台机器上的任何maven步骤中使用(不要忘记在pom中使用<dependency></dependency>标记将这个依赖项作为其他maven依赖项)。也可以不将jar安装绑定到初始化步骤,而是绑定到您喜欢的任何其他步骤。

依赖关系的重要部分是:${pom.basedir}(而不仅仅是${basedir})

<dependency>
    <groupId>org.example</groupId>
    <artifactId>example</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${pom.basedir}/src/lib/example.jar</systemPath>
</dependency>

在本地存储库中,您可以通过发出以下命令来安装jar

 mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

点击这个有用的链接,从mkyoung的网站进行同样的操作。您也可以查看maven指南

在maven项目的根目录创建一个新文件夹,比如本地maven repo。

只需在pom.xml的<project>中添加一个本地repo:

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

然后,对于要安装的每个外部jar,转到项目的根目录并执行:

mvn deploy:deploy-file -DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] -Durl=file:./local-maven-repo/ -DrepositoryId=local-maven-repo -DupdateReleaseInfo=true -Dfile=[FILE_PATH]

当然,您可以将jar添加到该文件夹中。但也许这并不是你想要实现的。。。

如果您需要这些jar进行编译,请检查这个相关问题:我可以在不安装jar的情况下将它们添加到maven 2构建类路径吗?

此外,在任何人提出建议之前,不要使用系统范围。