Maven: Local is the New Remote

Often I stumble into a case where I need to use Maven, but also use specific, non-published .jar files. In Ant’s world, you’d just throw these in a local directory in the project’s dir. That would be simple. Handling the transitive dependencies of the rest of the jars would not be. Which is why Maven rocks and we should all be using it.

But then there are the local-only jars.

So here is the solution I ended up using: have a local repository in the project’s directory, and deploy the jars there. This way, that repository can go into your version control system (i.e. git repo) and you can use Maven normally. Here’s how it’s done.

a) Create local repository. This is easy, just make a directory, and call it “lib” or something.

b) Register the repository in your pom.xml. Like so:

<repositories>
  <repository>
    <id>project.local</id>
    <name>project</name>
    <url>file:${project.basedir}/lib</url>
  </repository>
</repositories>

c) Add a jar to that repo. This is done from the commandline, using mvn:deploy-file command:

mvn deploy:deploy-file \
-Dfile=/path/to/jarfile.jar  \
-Durl=file:///path/to/the/project/lib/ \
-DgroupId=somegroupname \
-DartifactId=artifactname \
-Dversion=0.9 \
-Dpackaging=jar \

Clarifications:

  1. backslashes (“\”) are for escaping new lines, so the command is easier to read. They can be omitted, along with the newlines (“\n”s).
  2. version 0.9 is as made up as the group name and the artifact id.

d) Use your jar the Maven way by adding it as a dependency

<dependencies>
     <dependency>
         <groupId>somegroupname</groupId>
         <artifactId>artifactname</artifactId>
         <version>0.9</version>
     </dependency>
    ... regular dependencies ...
</dependencies>

That’s it! Pretty simple, and now that I’ve finally written it down, I won’t have to search for this solution over and overt again. Hopefully.


1 thought on “Maven: Local is the New Remote

  1. David Ziegler

    Great post!
    Another interesting option is to override the local Maven repository path.
    This worked for me in IntelliJ.
    Overriding the Maven local repo path in the settings to a folder within my project,
    allowed me to just put the deployed libraries in that same folder, and it works without adding any additional code to the POM file!
    For all I know, Maven works with a single local repository, and every library is downloaded to that location. Your libraries are also treated as remote libraries so they will also be copied there.
    So another advantage is that it won’t have to move the libraries into the local repo, as they’re already in it.
    There is a downside to this though.
    All other libraries used in the project will be downloaded into that folder in the project, which might get quite messy.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code