创建 JAR 文件而不包含外部依赖项

2022-01-15 00:00:00 dependencies java jar manifest

是否可以创建需要外部依赖项的 JAR 文件而不在 JAR 文件中包含这些依赖项?

Is it possible to create a JAR file that requires external dependencies without including those dependencies in the JAR file?

我的 google-fu 没有给我答案;我发现的所有内容都显示了如何将它们包含在 JAR 文件中,而不是在清单文件中放入什么来表示我没有得到它们,请查看用户的类路径".我会假设依赖项已在用户的类路径上正确安装和配置.

My google-fu has failed to give me an answer; everything that I have found shows how to include them in the JAR file, but not what to put in the manifest file to say "I haven't got them, look in the user's classpath". I would assume that the dependencies are properly installed and configured on the user's classpath.

就我而言,我的依赖项是 Apache Commons CLI 和 Math.

In my case, my dependencies are Apache Commons CLI and Math.

在我的 JAR 文件中,我有 Main.class.

Inside my JAR file, I have Main.class.

我的清单文件如下所示:

My manifest file looks like:

Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
Main-Class: Main

我的 CLASSPATH 看起来像

My CLASSPATH looks like

.;C:Program FilesJavajre1.6.0_06libextQTJava.zip;C:java_libcommons-cli-1.2.jar;C:java_libcommons-math-2.0commons-math-2.0.jar

如果我在 /lib 的 JAR 中包含依赖项并添加行 Class-Path: lib/commons-math-2.0.jar lib/commons-cli-1.2.jar 到清单,然后它就可以工作了.

If I include the dependencies in the JAR in /lib and add the line Class-Path: lib/commons-math-2.0.jar lib/commons-cli-1.2.jar to the manifest, then it does work.

我已尝试将 Class-Path: commons-math-2.0.jar commons-cli-1.2.jar 添加到清单中,但不包括 JAR 中的文件,只是为了看看这是否可行,但它没有.

I've tried adding Class-Path: commons-math-2.0.jar commons-cli-1.2.jar to the manifest without including the files in the JAR just to see if that would work, but it didn't.

推荐答案

使用META-INF/MANIFEST.MF 中的 "nofollow noreferrer">Class-Path 条目,以告知在哪里查找与您的 JAR 相关的依赖项.例如:

Use the Class-Path entry in the META-INF/MANIFEST.MF to tell where to look for dependencies relatively to your JAR. For example:

Class-Path: servlet.jar ../foo/bar.jar acme/beans.jar

相关文章