Intellij Java 2016 &Maven:如何在 JAR 中嵌入依赖项? [英] Intellij Java 2016 & Maven : how to embed dependencies in JAR?

查看:32
本文介绍了Intellij Java 2016 &Maven:如何在 JAR 中嵌入依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Intellij Java 2016.2.2 和 Maven 创建一个非常简单的 Java 控制台应用程序.

I'm using Intellij Java 2016.2.2 and Maven to create a very simple Java console application.

我想添加一个外部库,所以我在 Maven 中添加我的依赖项,如下所示:

I want to add an external library, so I add my dependency in Maven like this:

<dependency>
    <groupId>jline</groupId>
    <artifactId>jline</artifactId>
    <version>2.12</version>
</dependency>

当我在 IDE 中运行它时它运行良好,但在外部控制台中运行它却没有(我有以下错误:java.lang.NoClassDefFoundError).

It works fine when I run it in the IDE, but not in an external console (I have the following error: java.lang.NoClassDefFoundError).

我检查了,由于某种原因,我刚刚生成的 JAR 中没有添加外部 JAR.我也在文件 - >项目结构"中尝试了很多东西,但仍然无法正常工作......

I checked and for some reason, the external JAR is not added in the JAR I just generated. I also tried many things in "File -> Project Structure", but still not working...

我只想构建包含我的依赖项的 JAR,因此我可以使用以下命令在控制台中简单地运行我的应用程序:

I just want to build my JAR with my dependencies in it, so I can simply run my application in a console using:

java -jar myproject.jar

我该怎么做?感谢您的帮助!

How can I do that? Thanks for your help!

推荐答案

我终于设法用 Intellij Java 生成了这个 JAR,我是这样做的:

I finally managed to generate this JAR with Intellij Java, here is how I do:

  • 在 pom.xml 文件中添加依赖
  • 转到文件 -> 项目结构 -> 工件 -> 新建 -> JAR -> 来自具有依赖项的模块
  • 选择主类并点击确定
  • 在您的项目中,在 src/main 中,创建resources"文件夹
  • 将META-INF"(其中包含 MANIFEST.MF)文件夹移动到此资源"文件夹中
  • 转到构建 -> 构建工件以构建 JAR

编辑

一种更好(更简单)的方法是在 pom.xml 文件中添加以下行:

A better (and easier way) to do it is adding the following lines in the pom.xml file :

<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>your.MainClass</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

然后使用clean"和package"maven 命令.

then use the "clean" and "package" maven commands.

上面的最后 3 个步骤(关于 MANIFEST.MF)似乎仍然是强制性的.

The last 3 steps above (about MANIFEST.MF) still seem to be mandatory.

这篇关于Intellij Java 2016 &amp;Maven:如何在 JAR 中嵌入依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆