Alternative to fat jar in Gradle Java project 替代 Gradle Java 项目中的 Fat Jar

huangapple go评论74阅读模式
英文:

Alternative to fat jar in gradle java project

问题

我今天才开始使用Gradle。所以我正在尝试一些随机的东西。我有下面的build.gradle文件:

apply plugin: 'java'
repositories {
    mavenCentral()
}
 
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
    compile 'com.googlecode.json-simple:json-simple:1.1.1'
}

test {
    useJUnitPlatform()
}
jar {
  manifest {
    attributes(
      'Main-Class': 'src.main.java.demo.Hello'
    )
  }
  from {
     configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it)}        
   }
}

我在某处看到我在from块内部使用的方法会创建一个"fat jar",这不是一个好的做法。由于我对这方面还比较新,我谦卑地想要询问是否有其他替代方法。是将classpath添加到清单还是其他什么方法?

主要目的是捆绑第三方依赖的jar文件,这些文件将在运行时使用。

谢谢!

英文:

I have started on gradle today itself. So I am trying out random things. I have below build.gradle file:

apply plugin: 'java'
repositories {
    mavenCentral()
}
 
dependencies {
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.4.2')
    testRuntime('org.junit.jupiter:junit-jupiter-engine:5.4.2')
    compile 'com.googlecode.json-simple:json-simple:1.1.1'
    
}

test {
    useJUnitPlatform()
}
jar {
  manifest {
    attributes(
      'Main-Class': 'src.main.java.demo.Hello'
    )
  }
  from {
     configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it)}        
   }
}

I have read somewhere that the method that I am using inside from block will create fat jar, which is not a good practice. As I am fairly new to this, I humbly want to ask the alternative to this. Is it adding classpath to manifest or something else??

The primary purpose is to bundle third party dependency jar files that will be used on runtime.

Thank You!

答案1

得分: 1

你可以将所有依赖项与你自己的JAR文件以及可能的外部资源一起放入一个ZIP文件中,或者构建一个安装程序,或者(如果你正在构建一个Web应用程序)构建一个WAR或EAR文件。无论哪种情况,Gradle都会为你处理清单。

(此外,使用"fat JARs"也没有太大问题,这在当今相当常见,而且它们确实有效。)

英文:

You could put all your dependencies into a ZIP file together with your own JAR and possibly external resources, or build an installer, or (if you're building a web app) build a WAR or EAR file. Gradle will take care of the manifest for you in any case.

(Also, there is nothing really wrong with fat JARs, they are fairly common these days and they do work.)

huangapple
  • 本文由 发表于 2020年7月27日 22:48:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63117842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定