[英]How to compile Maven based Java project to run it from command line
I have a Maven project that I need somehow to compile so I'd be able to transfer the compiled file to a different machine and then execute there (with potentially different Java version). 我有一个Maven项目,我需要以某种方式进行编译,以便能够将已编译的文件传输到另一台计算机上,然后在该计算机上执行(可能使用不同的Java版本)。 I looked at this SO question
我看着这个问题
and was able to execute: 并能够执行:
mvn clean install
mvn dependency:copy-dependencies
Yet when I tried: 但是当我尝试:
cd target/
java -cp myApp-0.0.1.jar:dependency myApp
I got 我有
Error: Could not find or load main class myApp
My pom.xml does not have mvn-assembly-plugin or maven-jar-plugin (and I successfully get the .jar in target/ after mvn clean install). 我的pom.xml没有mvn-assembly-plugin或maven-jar-plugin(并且在mvn全新安装后,我在target /中成功获取了.jar)。
I am not sure whether those steps are related to my goal because what I need is to create something that will run without any java -jar or mvn and could be ported and run on a different machine. 我不确定这些步骤是否与我的目标相关,因为我需要创建的东西可以在没有任何java -jar或mvn的情况下运行,并且可以移植并在其他机器上运行。
There is Maven build plugin that would bundle all your dependencies in a JAR. 有一个Maven构建插件,它将您的所有依赖项捆绑在一个JAR中。 You could execute it simply with
您可以简单地执行它
java -jar mybundled.jar
without caring about class path dependencies. 无需关心类路径依赖关系。
And here comes the Maven
plugin. 这里是
Maven
插件。 Replace the MainClass
with your entry point. 用入口点替换
MainClass
。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.yourdomain.Main</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
As it is bound to the package lifecycle
, you would find your bundled JAR in your target directory after doing a ... 由于它与
package lifecycle
,因此在执行完...之后,您将在目标目录中找到捆绑的JAR。
mvn package
Regarding your concern that your code won't run on another machine, Java is platform-independent and generally you can rely on that. 关于您的代码不会在另一台计算机上运行的担忧,Java与平台无关, 通常您可以依靠它。 However, three things come to my mind that can make life hard:
但是,我想到了三件事可能会使生活变得艰难:
ps
won't work on windows and dir /s
probably not on *nix. ps
不能在Windows上运行,而dir /s
可能无法在* nix上运行。 source
and target
compile options, too: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html#crosscomp-example source
和target
编译选项: http : //docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html#crosscomp-example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.