How to add local jar files to a Maven project?

后端 未结 30 3904
悲&欢浪女
悲&欢浪女 2020-11-21 04:58

How do I add local jar files (not yet part of the Maven repository) directly in my project\'s library sources?

30条回答
  •  無奈伤痛
    2020-11-21 05:31

    Firstly, I would like to give credit for this answer to an anonymous Stack Overflow user - I am pretty sure I've seen a similar answer here before - but now I cannot find it.

    The best option for having local JAR files as a dependency is to create a local Maven repository. Such a repository is nothing more than a proper directory structure with pom files in it.

    For my example: I have my master project on ${master_project} location and subproject1 is on ${master_project}/${subproject1}.

    Then I create a Maven repository in: ${master_project}/local-maven-repo.

    In the pom file in subproject1 located at ${master_project}/${subproject1}/pom.xml, the repository needs to be specified which would take file path as a URL parameter:

    
        
            local-maven-repo
            file:///${project.parent.basedir}/local-maven-repo
        
    
    

    The dependency can be specified as for any other repository. This makes your pom repository independent. For instance, once the desired JAR is available in Maven central, you just need to delete it from your local repo and it will be pulled from the default repo.

        
            org.apache.felix
            org.apache.felix.servicebinder
            0.9.0-SNAPSHOT
        
    

    The last but not least thing to do is to add the JAR file to local repository using -DlocalRepositoryPath switch like so:

    mvn org.apache.maven.plugins:maven-install-plugin:2.5.2:install-file  \
        -Dfile=/some/path/on/my/local/filesystem/felix/servicebinder/target/org.apache.felix.servicebinder-0.9.0-SNAPSHOT.jar \
        -DgroupId=org.apache.felix -DartifactId=org.apache.felix.servicebinder \
        -Dversion=0.9.0-SNAPSHOT -Dpackaging=jar \
        -DlocalRepositoryPath=${master_project}/local-maven-repo
    

    Once the JAR file is installed, your Maven repo can be committed to a code repository, and the whole set-up is system independent. (Working example in GitHub).

    I agree that having JARs committed to source code repo is not a good practice, but in real life, quick and dirty solutions are sometimes better than a full blown Nexus repo to host one JAR that you cannot publish.

提交回复
热议问题