我一直在开发一个 Java
项目并使用 Maven
对其进行管理。
该项目本身有许多第三方依赖项,例如 Box2d
、OpenGL
..
当我运行 mvn package
时,项目的自定义源代码被打包到 .jar
中,并且它的所有依赖项都放置在 .jar
旁边名为 lib
的文件夹中。
还使用 Windows
和 *nix
平台的启动脚本创建一个 bin
文件夹。 (程序集描述符如下)。
我想知道这是打包这个基于 Java 的应用程序的最佳方式吗?它适合公众消费吗?
或者单个 uber.jar
会更好吗?其中包含 1 个文件中的所有依赖项。
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<fileSets>
<fileSet>
<directory>${project.build.directory}/${project.artifactId}</directory>
<outputDirectory>/</outputDirectory>
<includes>
<include>/**</include>
</includes>
<excludes>
<exclude>bin/*</exclude>
</excludes>
</fileSet>
<fileSet>
<directory>${project.build.directory}/${project.artifactId}/bin</directory>
<lineEnding>keep</lineEnding>
<useDefaultExcludes>true</useDefaultExcludes>
<outputDirectory>bin</outputDirectory>
<includes>
<include>*</include>
</includes>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
</assembly>
最佳答案
有 3 种常见方法:
创建一个包含所有依赖类和资源的 uber-jar。
创建可执行 jar 并使用
Class-Path
list 属性指定依赖 jar 的位置。创建一个包装器脚本,在其中通过
CLASSPATH
环境变量或-cp
参数指定依赖 jar 的位置。
(还有其他更复杂的方法......但我不会在这里讨论它们。)
每种方法都有优点和缺点。
使用 uber-jar,用户(部署者、管理员)很难使用依赖项的替代版本。 (这可能是依赖项的许可要求!!)
使用
Class-Path
list 属性,存在一定程度的脆弱性。如果主 jar 或依赖 jar 未安装在预期位置,则应用程序将无法运行。修复损坏/不适当的 list 非常繁琐。使用包装器脚本方法(也可能是 list 方法),您可能需要针对不同平台的不同脚本(或属性)。
但正如您所看到的,不存在通用的“最佳方法”。 (如果有人告诉你相反的情况,他们就是在做出毫无根据的假设!)
关于java - 打包具有依赖项的 .jar 时的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25695832/