Programming

Gradle을 사용하여 종속성이있는 jar 작성

procodes 2020. 8. 6. 22:23
반응형

Gradle을 사용하여 종속성이있는 jar 작성


나는 다중 프로젝트 빌드를 가지고 있으며 하위 프로젝트 중 하나에 뚱뚱한 항아리를 만드는 작업을했습니다. 나는 요리 책에 설명 된 것과 비슷한 작업을 만들었습니다 .

jar {
  from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  manifest { attributes 'Main-Class': 'com.benmccann.gradle.test.WebServer' }
}

실행하면 다음 오류가 발생합니다.

원인 : 해결되지 않은 상태가 아닌 구성은 변경할 수 없습니다!

이 오류가 무엇을 의미하는지 잘 모르겠습니다. 또한 버그 인 경우를 대비하여 Gradle JIRA에서도이를보고했습니다 .


JIRA에 Gradle 대한 솔루션게시 했습니다 .

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

mainClassName전에 나타나야합니다 jar {.


jar작업이 정상적으로 작동 하고 추가 작업이되도록 fatJar하려면 다음을 사용하십시오.

task fatJar(type: Jar) {
    classifier = 'all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

중요한 부분은 with jar입니다. 그것 없이는이 프로젝트의 수업이 포함되지 않습니다.


@felix의 대답은 거의 나를 데려 왔습니다. 두 가지 문제가있었습니다.

  1. Gradle 1.5에서는 manifest 태그가 fatJar 작업 내에서 인식되지 않아 Main-Class 속성을 직접 설정할 수 없었습니다.
  2. 항아리에 충돌하는 외부 META-INF 파일이 있습니다.

다음 설정은이 문제를 해결합니다.

jar {
  manifest {
    attributes(
      'Main-Class': 'my.project.main',
    )
  }
}

task fatJar(type: Jar) {
  manifest.from jar.manifest
  classifier = 'all'
  from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } {
    exclude "META-INF/*.SF"
    exclude "META-INF/*.DSA"
    exclude "META-INF/*.RSA"
  }
  with jar
}

이것을 표준 어셈블 또는 빌드 태스크에 추가하려면 다음을 추가하십시오.

artifacts {
    archives fatJar
}

편집 : @mjaggard 감사 : Gradle을 최신 버전의 변경 configurations.runtimeconfigurations.runtimeClasspath


이것은 나를 위해 잘 작동합니다.

내 주요 수업 :

package com.curso.online.gradle;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class Main {

    public static void main(String[] args) {
        Logger logger = Logger.getLogger(Main.class);
        logger.debug("Starting demo");

        String s = "Some Value";

        if (!StringUtils.isEmpty(s)) {
            System.out.println("Welcome ");
        }

        logger.debug("End of demo");
    }

}

그리고 그것은 내 파일 build.gradle의 내용입니다.

apply plugin: 'java'

apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile  'org.apache.commons:commons-lang3:3.0'
    compile  'log4j:log4j:1.2.16'
}

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': 'com.curso.online.gradle.Main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

그리고 나는 내 콘솔에 다음을 씁니다.

java -jar ProyectoEclipseTest-all.jar

그리고 출력은 훌륭합니다.

log4j:WARN No appenders could be found for logger (com.curso.online.gradle.Main)
.
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
Welcome

서명 된 JAR의 문제를 피하고 기본 실행 가능 클래스로 fat JAR을 생성하려면 gradle-one-jar plugin을 제안 합니다. One-JAR 프로젝트 를 사용하는 간단한 플러그인 .

사용하기 쉬운:

apply plugin: 'gradle-one-jar'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.github.rholder:gradle-one-jar:1.0.4'
    }
}

task myjar(type: OneJar) {
    mainClass = 'com.benmccann.gradle.test.WebServer'
}

간단한 해결

jar {
    manifest {
        attributes 'Main-Class': 'cova2.Main'
    } 
    doFirst {
        from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}

The answer from @ben almost works for me except that my dependencies are too big and I got the following error

Execution failed for task ':jar'.
> archive contains more than 65535 entries.

  To build this archive, please enable the zip64 extension.

To fix this problem, I have to use the following code

mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  
  zip64 = true
  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

If you're used to ant then you could try the same with Gradle too:

task bundlemyjava{
    ant.jar(destfile: "build/cookmyjar.jar"){
        fileset(dir:"path to your source", includes:'**/*.class,*.class', excludes:'if any')
        } 
}

참고URL : https://stackoverflow.com/questions/4871656/using-gradle-to-build-a-jar-with-dependencies

반응형