Maven use local jar without installing

You can install a local jar by using  mvn install:install-file command/goal as I discussed in my earlier blog post. This ensures the re-usability of jar file across your projects but as a drawback, this requires every team member and build server to run the same command/goal to build their project.

To avoid to the manual hassle, you can add the .jar in pom.xml file without running the mvn install:install-file goal. The idea is to refer a .jar from your project base directory using the <systemPath> element.

In example below, I put my jar files to /myjars directory and point to the jar file as
        <systemPath>${project.basedir}/myjars/[Jar file name]</systemPath>

Directory Structure

..
/src/..
pom.xml
/myjars/my-lib-core.jar
/myjars/third-party.jar

Pom.xml

<dependencies>
    <dependency>
        <groupId>com.my.library</groupId>
        <artifactId>mylib-core</artifactId>
        <version>1.VERSION</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/myjars/my-lib-core.jar</systemPath>
    </dependency>
    <dependency>
        <groupId>com.third-party.library</groupId>
        <artifactId>thirdparty</artifactId>
        <version>1.VERSION</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/myjars/third-party.jar</systemPath>
    </dependency>

For web project (war files )

If you are working on a web project, the above configuration won't add the jars to war file by default. You need to do following.

Here we are asking maven-war-plugin to add all jar ( **/*.jar) from  ${project.basedir}/myjars  to WEB-INF/lib folder when creating the war file.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <warSourceDirectory>src/main/webapp/</warSourceDirectory>
                <webResources>
                    <resource>
                        <directory>${project.basedir}/myjars</directory>
                        <targetPath>WEB-INF/lib</targetPath>
                        <includes>
                            <include>**/*.jar</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
    </plugins>
</build>