back end/java

[java] gradle로 runnable jar 생성하는 방법

노루아부지 2023. 2. 9. 17:05
반응형

Eclipse의 경우 기본 java 프로젝트는 "Export..."를 통해 runnable jar를 만들었지만, gradle을 사용할 경우 "Export..."를 사용할 수 없습니다.

 

이 경우 다음과 같이 진행할 수 있습니다.

 

gradle로 runnable jar 생성하는 방법

1. build.gradle에 shadow plugin 추가

plugins {
    id 'com.github.johnrengelman.shadow' version '6.1.0'
}

 

2. build.gradle에 다음 코드 추가

jar {
	finalizedBy shadowJar

	manifest {
		attributes 'Main-Class': 'com.gradle.TestClass'
	}
}

 

3. gradle clean, gradle build, gradle jar를 차례대로 실행

gradle로 runnable jar 생성하는 방법

 

 

4. project/lib/build/libs 경로로 이동하여 "project명-all.jar" 파일 실행

libs 경로로 이동하면 작성한 코드만 들어있는 project.jar 파일과, dependency가 모두 포함된 project-all.jar 파일이 생성됩니다.

다음 명령어를 사용하여 all.jar를 실행합니다.

java -jar project-all.jar

 

 

 

 

실패한 방법

인터넷에 검색하면 plugin을 사용하지 않고, 직접 build하는 방법이 많이 나옵니다.

jar {
    manifest {
        attributes 'Main-Class': 'com.test.gradle.AppStart'
    }
}

 

이렇게 입력하고 build하면 dependency가 없는 상태로 빌드됩니다.

 

jar {
    manifest {
        attributes 'Main-Class': 'com.test.gradle.AppStart'
    }
    // 이 부분 추가
    from {
        configurations.compile.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
}

dependency를 추가한 방법에 따라서 compile.collect / runtimeClasspath.collect / compileClasspath.collect 등으로 변경할 수 있는데, 이 코드를 추가하면 dependency가 추가됩니다.

다만, 이대로 실행하면 duplicate but no duplicate handling strategy has been set 오류가 발생하는데 아래와 같이 하면 해결됩니다.

 

jar {
    manifest {
        attributes 'Main-Class': 'com.test.gradle.AppStart'
    }
    from {
        configurations.runtimeClasspath.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
    // 이 부분 추가
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

 여기까지 하고 실행하면 다음과 같은 오류가 발생합니다.

  • 오류: 기본클래스 xxx을(를) 찾거나 로드할 수 없습니다.
  • Error: Could not find or load main class xxx

 

이 오류를 해결하지 못하여 shadow plugin을 사용했습니다.

 

 

 

 

 

[참고 사이트]

https://stackoverflow.com/questions/21721119/creating-runnable-jar-with-gradle

 

Creating runnable JAR with Gradle

Until now I created runnable JAR files via the Eclipse "Export..." functionallity but now I switched to IntelliJ IDEA and Gradle for build automation. Some articles here suggest the "application" ...

stackoverflow.com

https://lemontia.tistory.com/1056

 

[gradle] intellij 에서 gradle을 이용해 runnable jar 만들기

jar를 만드는 방법은 두가지가 있다. 1) gradle 에 설정한 뒤, tasks -> jar 를 실행하여 만드는 방법 2) intellij 프로젝트 Settings 에서 artifacts를 등록하여 만드는 방법 2번의 경우 새로운 Intellij 환경마다

lemontia.tistory.com

https://empty-castle.tistory.com/1

 

[Gradle]Gradle에서 Runnable.jar 만들기

Result jar { manifest { attributes 'Version': version, 'Main-Class': mainClassName } from { configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) } } } build.gradle에 이렇게 코드를 추가해주세요. 주저리주저리 Gradl

empty-castle.tistory.com

 

728x90
반응형
loading