[英]Running jar, setting classpath
I've got a project I've made with Maven. 我有一个我用Maven制作的项目。 I compile a JAR, with "mvn package", and now I want to run it, preferably without setting some insane classpath, as it depends on Spring and half the internet or something.
我使用“mvn package”编译了一个JAR,现在我想运行它,最好不要设置一些疯狂的类路径,因为它依赖于Spring和一半的互联网或其他东西。 Is there any way I can run it easily?
有什么办法可以轻松运行吗? Something like "mvn run" would be great, or an option to throw in all dependencies into the jar so I can do "java -jar" would also be splendid.
像“mvn run”之类的东西会很棒,或者是将所有依赖项都放入jar中的选项,所以我可以做“java -jar”也很精彩。
How do you deal with this, and what do you recommend doing? 你是如何处理这个的,你建议做什么? Because exporting a CLASSPATH based on ~/.m2 would probably just be hurtful ;-)
因为基于〜/ .m2导出CLASSPATH可能只是伤害;-)
Setting CLASSPATH
and calling java -jar myjar.jar
wouldn't work anyway. 设置
CLASSPATH
并调用java -jar myjar.jar
无论如何都行不通。 Because the java -jar
command ignores the CLASSPATH
environment variable as well as the -cp
flag. 因为
java -jar
命令忽略CLASSPATH
环境变量以及-cp
标志。
In this case you had to add the classpath entries to the jar's MANIFEST at the Class-Path
key, like: 在这种情况下,您必须在
Class-Path
键中将类路径条目添加到jar的MANIFEST中,如:
Class-Path: jar1-name jar2-name directory-name/jar3-name
Use the Maven Assembly Plugin - it will automatically build your JAR with all included dependencies, and you can set the main class parameter to make the JAR executable. 使用Maven Assembly Plugin - 它将自动构建包含所有包含依赖项的JAR,并且可以设置主类参数以使JAR可执行。
The documentation can be confusing, so here is an example of what your POM will look like: 文档可能会令人困惑,因此以下是POM的示例:
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>package.of.my.MainClass</mainClass>
<packageName>package.of.my</packageName>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
And then you can run as: 然后你可以运行:
mvn assembly:assembly
You will want to look into the Maven Assembly Plugin . 您将需要查看Maven Assembly插件 。 And then once you have created the XML file required by the plugin and have modified your POM file to work with the plugin, you can run it with:
然后,一旦您创建了插件所需的XML文件并修改了您的POM文件以使用该插件,您就可以使用以下命令运行它:
mvn assembly:assembly
This will create the JAR with all of its dependencies. 这将创建具有所有依赖项的JAR。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.