Sunday, June 5, 2016

How to add custom/local jars to a maven project as in-project repository

There are certain times when you will need to add a custom jar that is not present in a central or local repository as part of the maven build/compile goals. This jar along with others would need to be shipped out as part of the jar depdencies that are needed for the program to run. If you encounter such a suitation then follow the steps below to add the custom/local jar to your project.

1) Create a folder called 'lib' in your project root hierarchy.
For example if you have a project called c:\myTestProject then create a folder c:\myTestProject\lib

2) Copy the jar file to c:\myTestProject
For example lets say that we need to add a jar called abcd.jar to our project. So copy abcd.jar to c:\myTestProject\abcd.jar

3) Using maven 2.3 onwards, from windows command line, issue the command
mvn install:install-file -Dfile=c:\myTestProject\abcd.jar -DgroupId=com.xyz.myproject -DartifactId=abcd -Dversion=1.0.0 -Dpackaging=jar -DlocalRepositoryPath=c:\myTestProject\lib -DgeneratePom=true

After running that command, you will see the below folder created with the jar in it
c:\myTestProject\lib\com\xyz\myproject\abcd-1.0.0.jar


Now you can delete the c:\myTestProject\abcd.jar

4) Make the below changes to your projects pom.xml file

Note: file://${project.basedir}\lib has a \lib (backlash\lib) which is needed to work on windows computers
 

<project>
...
...

<repositories>
  <repository>
    <id>my-local-repo</id>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
    <url>file://${project.basedir}\lib</url>
  </repository>
</repositories>

<dependencies>
    <dependency>
         <groupId>com.xyz.myproject</groupId>
        <artifactId>abcd</artifactId>
        <version>1.0.0</version>
    </dependency>
    ...
    ...
</dependencies>

...
...
<project>

After following the above steps, if you are still not able to build the project using maven and maven says that it cannot locate the abcd.jar file then check the maven settings ${maven_home}\.m2\settings.xml file
set the <mirrorOf> tag as mentioned below

<mirrors>
    <mirror>
        <mirrorOf>*<mirrorOf>
        ...
        ...
    </mirror>
</mirrors>

No comments: