Program Tip

Maven 프로젝트에 로컬 jar 파일을 추가하는 방법은 무엇입니까?

programtip 2020. 9. 27. 13:50
반응형

Maven 프로젝트에 로컬 jar 파일을 추가하는 방법은 무엇입니까?


내 프로젝트의 라이브러리 소스에 직접 로컬 jar 파일 (아직 Maven 저장소의 일부가 아님)을 추가하려면 어떻게해야합니까?


다음과 같이 로컬 Maven 저장소에 JAR을 설치합니다.

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

각각은 다음을 의미합니다.

<path-to-file>:로드 할 파일 경로 예 : → c:\kaptcha-2.3.jar

<group-id>: 파일이 등록되어야하는 그룹 예 : → com.google.code

<artifact-id>: 파일의 아티팩트 이름 예 : → kaptcha

<version>: 파일 버전 예 : → 2.3

<packaging>: 파일 포장 예 → jar

참고


다음과 같이 로컬 종속성을 직접 추가 할 수 있습니다 ( 독점 라이브러리가 포함 된 빌드 메이븐 프로젝트 에서 언급 됨 ).

<dependency>
    <groupId>com.sample</groupId>
    <artifactId>sample</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${project.basedir}/src/main/resources/Name_Your_JAR.jar</systemPath>
</dependency>

최신 정보

새 릴리스에서이 기능은 더 이상 사용되지 않는 것으로 표시되지만 여전히 작동하며 아직 제거되지 않았습니다 (Maven 시작 중에 로그에 경고 만 표시됨). https://issues.apache.org/jira/browse/MNG-6523 에 대해 maven 그룹에서 문제가 발생했습니다 (이 기능이 어떤 경우에 도움이되는 이유에 참여하고 설명 할 수 있음). 이 기능이 그대로 남아 있기를 바랍니다.

당신이 저를 요구하는 경우, 한 기능이 제거되지 않는 한, 나는 이것을 사용 에만 의존을 하나 개의 나쁜 jar 파일 저장소에 적합하지 않습니다 내 프로젝트이다. 이 기능이 제거되면 나중에 선택할 수있는 좋은 답변이 많이 있습니다!


첫째, 익명의 Stack Overflow 사용자에게이 답변에 대한 크레딧을 제공하고 싶습니다. 이전에 유사한 답변을 본 적이 있지만 지금은 찾을 수 없습니다.

로컬 JAR 파일을 종속성으로 사용하는 가장 좋은 옵션은 로컬 Maven 저장소를 만드는 것입니다. 이러한 저장소는 pom 파일이있는 적절한 디렉토리 구조에 지나지 않습니다.

내 예 : 마스터 프로젝트가 ${master_project}위치에 있고 subproject1이 on ${master_project}/${subproject1}입니다.

그런 다음 Maven 저장소를 ${master_project}/local-maven-repo.

에있는 subproject1의 pom 파일에서 ${master_project}/${subproject1}/pom.xml파일 경로를 URL 매개 변수로 사용하는 저장소를 지정해야합니다.

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

다른 저장소와 마찬가지로 종속성을 지정할 수 있습니다. 이것은 당신의 pom 저장소를 독립적으로 만듭니다. 예를 들어 Maven 중앙에서 원하는 JAR을 사용할 수있게되면 로컬 리포지토리에서 삭제하기 만하면 기본 리포지토리에서 가져옵니다.

    <dependency>
        <groupId>org.apache.felix</groupId>
        <artifactId>org.apache.felix.servicebinder</artifactId>
        <version>0.9.0-SNAPSHOT</version>
    </dependency>

마지막으로 할 일은 다음과 같이 -DlocalRepositoryPath 스위치를 사용하여 JAR 파일을 로컬 저장소에 추가하는 것입니다.

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

JAR 파일이 설치되면 Maven 리포지토리를 코드 저장소에 커밋 할 수 있으며 전체 설정은 시스템 독립적입니다. ( GitHub의 작업 예제 ).

나는 JAR을 소스 코드 저장소에 커밋하는 것이 좋은 습관이 아니라는 데 동의하지만 실제로는 빠르고 더러운 솔루션이 게시 할 수없는 하나의 JAR을 호스팅하는 완전한 Nexus 저장소보다 낫습니다.


local-maven-repoMaven 프로젝트의 루트에 새 폴더를 만듭니다 .

귀하 <project>내부에 로컬 저장소를 추가 하십시오 pom.xml.

<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]

그런 솔루션을 원합니다 maven-install-plugin-pom 파일에서 사용 하십시오.

        <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 initialize있으며 jar는 로컬 maven repo에 설치됩니다. 이제이 jar는이 머신의 모든 maven 단계에서 사용할 수 있습니다 ( <dependency></dependency>태그가 있는 pom의 다른 maven 종속성으로이 종속성을 포함하는 것을 잊지 마십시오 ). jar install을 initialize단계가 아닌 원하는 다른 단계 에 바인딩 할 수도 있습니다 .


<dependency>
    <groupId>group id name</groupId>
    <artifactId>artifact name</artifactId>
    <version>version number</version>
    <scope>system</scope>
    <systemPath>jar location</systemPath>
</dependency>

예, 가질 수는 있지만 좋은 생각은 아닙니다.

대신이 모든 jar를 maven repos에 설치하십시오.

참조


한 가지 방법은 자신의 Maven 저장소 관리자 (예 : Nexus)에 업로드하는 것입니다. 어쨌든 자신의 저장소 관리자를 갖는 것이 좋습니다.

내가 최근에 본 또 다른 좋은 방법은 빌드 라이프 사이클에 Maven 설치 플러그인을 포함하는 것입니다. POM에서 선언하여 로컬 저장소에 파일을 설치합니다. 약간의 오버 헤드이며 수동 단계가 필요하지 않습니다.

http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html


POM 파일에 자신의 로컬 JAR을 추가하고 Maven 빌드에서 사용하십시오.

mvn install:install-file -Dfile=path-to-jar -DgroupId=owngroupid -DartifactId=ownartifactid -Dversion=ownversion -Dpackaging=jar

예를 들면 :

mvn install:install-file -Dfile=path-to-jar -DgroupId=com.decompiler -DartifactId=jd-core-java -Dversion=1.2 -Dpackaging=jar

그런 다음 다음과 같이 POM에 추가합니다.

여기에 이미지 설명 입력


정말 빠르고 더러운 방법은 로컬 파일을 가리키는 것입니다.

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

그러나 이것은 (분명히) 귀하의 컴퓨터에만 존재합니다. 공유를 위해 일반적으로 적절한 m2 아카이브 (nexus / artifactory)를 사용하는 것이 합리적이거나 이러한 아카이브가 없거나 로컬 메이븐을 설정하고 싶지 않은 경우 구조화 된 아카이브를 만들고 pom : local에서 "저장소"를 구성합니다.

<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>

물론 해당 폴더에 jar를 추가 할 수 있습니다. 하지만 당신이 원하는 것이 아닐 수도 있습니다 ...

컴파일을 위해 이러한 jar가 필요한 경우 다음 관련 질문을 확인 하십시오. jar를 설치하지 않고 maven 2 빌드 클래스 경로에 추가 할 수 있습니까?

또한 누군가가 제안하기 전에 시스템 범위를 사용하지 마십시오.


명령 줄 :

mvn install:install-file -Dfile=c:\kaptcha-{version}.jar -DgroupId=com.google.code
-DartifactId=kaptcha -Dversion={version} -Dpackaging=jar

또 다른 흥미로운 경우는 프로젝트에 개인 maven jar를 포함하려는 경우입니다. 전 이적 종속성을 해결하기 위해 Maven의 기능을 유지할 수 있습니다. 해결책은 상당히 쉽습니다.

  1. 프로젝트에 libs 폴더 만들기
  2. pom.xml 파일에 다음 줄을 추가합니다.

    <properties><local.repository.folder>${pom.basedir}/libs/</local.repository.folder>
    </properties>
    
    <repositories>
       <repository>
            <id>local-maven-repository</id>
            <url>file://${local.repository.folder}</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
       </repository>
    </repositories>
    
  3. .m2 / repository 폴더를 열고 libs 폴더 로 가져 오려는 프로젝트의 디렉토리 구조를 복사하십시오 .

예를 들어 종속성을 가져오고 싶다고 가정합니다.

<dependency>
    <groupId>com.mycompany.myproject</groupId>
    <artifactId>myproject</artifactId>
    <version>1.2.3</version>
</dependency>

.m2 / repository 로 이동 하면 다음 폴더가 표시됩니다.

com / mycompany / myproject / 1.2.3

libs 폴더의 모든 항목 ( .m2 / repository 아래의 폴더 포함)을 복사 하면 완료됩니다.


선호하는 방법은 자신의 원격 저장소를 만드는 것입니다.

방법에 대한 자세한 내용 여기참조 하십시오 . ' 원격 저장소에 업로드 '섹션을 살펴보십시오.


이 문제에 대한 더 나은 해결책은 maven-install-plugin 을 사용하여 설치시 파일을 자동으로 설치하는 것입니다. 이것이 내 프로젝트를 위해 설정하는 방법입니다.

먼저 경로 (로컬 .jars를 저장하는 위치)를 속성으로 추가합니다.

<properties>
    <local.sdk>/path/to/jar</local.sdk>
</properties>

그런 다음 plugins컴파일 할 때 jar를 설치하는 플러그인을 추가하십시오.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-install-plugin</artifactId>
    <version>2.5.2</version>
    <executions>
        <execution>
            <id>1</id>
            <phase>initialize</phase>
            <goals>
                <goal>install-file</goal>
            </goals>
            <configuration>
                <groupId>com.local.jar</groupId> 
                <artifactId>appengine-api</artifactId>
                <version>1.0</version>
                <packaging>jar</packaging>
                <file>${local.sdk}/lib/impl/appengine-api.jar</file>
            </configuration>
        </execution>
        <execution>
            <id>appengine-api-stubs</id>
            <phase>initialize</phase>
            <goals>
                <goal>install-file</goal>
            </goals>
            <configuration>
                <groupId>com.local.jar</groupId>
                <artifactId>appengine-api-stubs</artifactId>
                <version>1.0</version>
                <packaging>jar</packaging>
                <file>${local.sdk}/lib/impl/appengine-api-stubs.jar</file>
            </configuration>
        </execution>
    </executions>
</plugin>

마지막으로 종속성에서 jar를 추가 할 수 있습니다.

<dependency>
    <groupId>com.local.jar</groupId>
    <artifactId>appengine-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>com.local.jar</groupId>
    <artifactId>appengine-api-stubs</artifactId>
    <version>1.0</version>
    <scope>test</scope>
</dependency>

이와 같이 프로젝트를 설정하면 다른 컴퓨터로 가져가도 프로젝트가 계속 빌드됩니다 (속성에 지정된 경로에 모든 jar 파일이있는 경우 local.sdk).

For groupId use a unique name just to make sure that there are no conflicts.

Now when you mvn install or mvn test local jars will be added automatically.


Also take a look at...

<scope>compile</scope>

Maven Dependencies. This is the default but I've found in some cases explicitly setting that scope also Maven to find local libraries in the local repository.


I want to share a code where you can upload a folder full of jars. It's useful when a provider doesn't have a public repository and you need to add lots of libraries manually. I've decided to build a .bat instead of call directly to maven because It could be Out of Memory errors. It was prepared for a windows environment but is easy to adapt it to linux OS:

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class CreateMavenRepoApp {

    private static final String OCB_PLUGIN_FOLDER = "C://your_folder_with_jars";

    public static void main(String[] args) throws IOException {

    File directory = new File();
    //get all the files from a directory
    PrintWriter writer = new PrintWriter("update_repo_maven.bat", "UTF-8");
    writer.println("rem "+ new Date());  
    File[] fList = directory.listFiles();
    for (File file : fList){
        if (file.isFile()){               
        String absolutePath = file.getAbsolutePath() ;
        Manifest  m = new JarFile(absolutePath).getManifest();
        Attributes attributes = m.getMainAttributes();
        String symbolicName = attributes.getValue("Bundle-SymbolicName");

        if(symbolicName!=null &&symbolicName.contains("com.yourCompany.yourProject")) {
            String[] parts =symbolicName.split("\\.");
            String artifactId = parts[parts.length-1];
            String groupId = symbolicName.substring(0,symbolicName.length()-artifactId.length()-1);
            String version = attributes.getValue("Bundle-Version");
            String mavenLine= "call mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file -Dfile="+ absolutePath+" -DgroupId="+ groupId+" -DartifactId="+ artifactId+" -Dversion="+ version+" -Dpackaging=jar ";
            writer.println(mavenLine);          
        }

        }
    }
    writer.close();
    }

}

After run this main from any IDE, run the update_repo_maven.bat.


This is a short syntax for newer versions:

mvn install:install-file -Dfile=<path-to-file>

It works when the JAR was built by Apache Maven - the most common case. Then it'll contain a pom.xml in a subfolder of the META-INF directory, which will be read by default.

Source: http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html


Note that it is NOT necessarily a good idea to use a local repo. If this project is shared with others then everyone else will have problems and questions when it doesn't work, and the jar won't be available even in your source control system!

Although the shared repo is the best answer, if you cannot do this for some reason then embedding the jar is better than a local repo. Local-only repo contents can cause lots of problems, especially over time.


On your local repository you can install your jar by issuing the commands

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

Follow this useful link to do the same from mkyoung's website. You can also check maven guide for the same


For some reason, in the web application I'm giving maintenance to, neither Alireza Fattahi's solution nor JJ Roman's solution worked correctly. In both cases, the compilation goes okay (it sees the jar), but the packaging fails to include the jar inside the war.

The only way I managed to make it work was by putting the jar on /src/main/webapp/WEB-INF/lib/ and then combining it with either Fattahis's or Roman's solution.


THIS ANSWER IS ONLY FOR ECLIPSE USERS:

If you are using Eclipse, place the jar in lib/, right click on the jar name and click "add to build path". Eclipse will create a "referenced libraries" and place the jar for you

It resolved the import of the jar right away in the program for me


To install third party jar, Please call the command like below

mvn install:install-file -DgroupId= -DartifactId= -Dversion= -Dpackaging=jar -Dfile=path

I had the same error for a set of dependencies in my pom.xml turns out the versions of the dependencies was not specified in the pom.xml and was mentioned in the parent repository. For some reason the version details was not syncing with this repo. Hence i manually entered the versions using the tag and it worked like a charm. Little bit of time needed to look up the versions in the parent and specify here. But this can be done just for the jars that are showing the artifactid error and it works. Hope this helps someone.


  1. mvn install

You can write code below in command line or if you're using eclipse builtin maven right click on project -> Run As -> run configurations... -> in left panel right click on Maven Build -> new configuration -> write the code in Goals & in base directory :${project_loc:NameOfYourProject} -> Run

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

Where each refers to:

< path-to-file >: the path to the file to load e.g -> c:\kaptcha-2.3.jar

< group-id >: the group that the file should be registered under e.g -> com.google.code

< artifact-id >: the artifact name for the file e.g -> kaptcha

< version >: the version of the file e.g -> 2.3

< packaging >: the packaging of the file e.g. -> jar

2.After installed, just declares jar in pom.xml.

 <dependency>
      <groupId>com.google.code</groupId>
      <artifactId>kaptcha</artifactId>
      <version>2.3</version>
 </dependency>

Apache Maven 3.5.4에서는 큰 따옴표를 추가해야했습니다. 큰 따옴표 없이는 저에게 효과가 없었습니다.

예 : mvn install : install-file "-Dfile = jar 파일 위치" "-DgroupId = group id" "-DartifactId = artifact id" "-Dversion = version" "-Dpackaging = package type"


ojdbc6에서도 같은 문제가 발생했습니다. 이 링크를 보았지만 작동하지 않았습니다. 명령은 맞았지만 매개 변수가 하나 더 필요했습니다.

이것은 링크입니다 : http://roufid.com/3-ways-to-add-local-jar-to-maven-project/

다음은 그 예입니다.

install:install-file -Dfile=C:\driversDB\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar

참고 URL : https://stackoverflow.com/questions/4955635/how-to-add-local-jar-files-to-a-maven-project

반응형