运行 java -jar 时包含外部 jar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2910115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:23:07  来源:igfitidea点击:

include external jar when running java -jar

javajarclasspathmanifest.mf

提问by rouble

From my readings, when you execute a command as follows:

根据我的阅读,当您执行如下命令时:

java -jar foo.jar

Then the main classpath is ignored, and the classpath is taken from the manifest file.

然后忽略主类路径,并从清单文件中获取类路径。

Further, the classpath declared on the command line is also ignored. So in:

此外,在命令行上声明的类路径也被忽略。所以在:

java -classpath /usr/local/jar/foobar.jar -jar foo.jar

/usr/local/jar/foobar.jar is ignored.

/usr/local/jar/foobar.jar 被忽略。

Lastly, I have read that the manifest file can only contain relative paths, within the jar file.

最后,我读到清单文件只能包含 jar 文件中的相对路径。

So, how do you include absolute paths to external jars, that are present on the system, but not in the jar file being executed?

那么,如何包含系统上存在但不在正在执行的 jar 文件中的外部 jar 的绝对路径?

采纳答案by matt b

Is there a reason why you are avoiding invoking the main class like

您是否有理由避免调用主类,例如

java -cp /usr/local/jar/foobar.jar:/some/other/path.jar com.your.main.classname

?

?

This type of invocation allows you to mix absolute paths with relative paths. Put this into a shell script or batch file to avoid having to actually type or remember the full classpath to simplify things.

这种类型的调用允许您将绝对路径与相对路径混合使用。将其放入 shell 脚本或批处理文件中,以避免必须实际键入或记住完整的类路径以简化事情。

回答by Gaurav Vaish

You can create a folder, say lib, within the folder where you have the jar file.

您可以在包含 jar 文件的文件夹中创建一个文件夹,比如 lib。

Manifest.MF contents can be:

Manifest.MF 内容可以是:

Main-Class: com.mastergaurav.test.app.MainClass
Class-Path: lib/one.jar lib/two.jar

Folder contents:

文件夹内容:

mainFolder/
   * lib/one.jar
   * lib/two.jar
   * my-main.jar

To execute:

执行:

java -jar my-main.jar