如何使用maven打包和运行具有依赖项的简单命令行应用程序? [英] How do I package and run a simple command-line application with dependencies using maven?
问题描述
我对java和maven都是陌生的,所以这很简单.
I am brand new to both java and to maven, so this is likely very simple.
如果我在这里按照maven2 hello world
的说明进行操作:
If I follow the maven2 hello world
instructions here:
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
一切正常.然后,如果我更改pom.xml
以从远程存储库引入依赖项,则此依赖项的文件将存储在~/.m2/repository/new-dependency/
中.
everything works OK. If I then alter pom.xml
to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/
.
使用hello world
指令中的语法来运行应用程序,要求我将绝对路径添加到类路径的依赖项中(通过设置环境变量或通过命令行开关):
Using the syntax in the hello world
instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):
java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App
这显然会很快变得笨拙:)
This will obviously get unwieldy quickly :)
我怀疑这不是运行Java程序的常用方法,我只需要阅读有关.jar文件的更多信息,但是在我这样做的同时,我将感谢您提供有关如何正确执行此操作的所有提示.
I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.
我不使用IDE,顺便说一句.命令行中的vim.
I am not using an IDE, btw. vim from the command line.
谢谢!
迈克.
推荐答案
您可以通过将Main-Class属性添加到其清单文件来使jar成为可执行文件.在Maven中,这是由存档程序插件完成的.要添加Main-Class属性,请将其添加到pom.xml:
You can make a jar executable by adding the Main-Class attribute to its manifest file. In Maven this is done by the archiver plugin. To add the Main-Class attribute, add this to your pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.mycompany.app.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
您现在可以使用以下命令运行jar:java -jar myjar.jar
或双击它(并非在所有平台上都可用).
You can now run your jar with the command: java -jar myjar.jar
or by double clicking on it (not available in all platforms).
这篇关于如何使用maven打包和运行具有依赖项的简单命令行应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!