Java 将外部库添加到 IntelliJ IDEA 中的工件 jar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42196697/
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-11 23:58:34  来源:igfitidea点击:

Adding external library to artifact jar in IntelliJ IDEA

javamavenintellij-ideabuilddependencies

提问by Shivashriganesh Mahato

How can I add an external library to a project in IntelliJ IDEA so that when I build an artifact it still has access to the classes in the library?

如何将外部库添加到 IntelliJ IDEA 中的项目,以便在构建工件时它仍然可以访问库中的类?

I have created a new Jar artifact from Project Structure, then added the external JAR to the Libraries, then checked it in the Modules List, and finally added it to the Output for the Artifact. None of these work. When I build and try running my application, it throws an error:

我从项目结构创建了一个新的 Jar 工件,然后将外部 JAR 添加到库中,然后在模块列表中检查它,最后将其添加到工件的输出中。这些都不起作用。当我构建并尝试运行我的应用程序时,它抛出一个错误:

Exception in thread "main" java.lang.NoClassDefFoundError: <path of the class trying to use>

Exception in thread "main" java.lang.NoClassDefFoundError: <path of the class trying to use>

What am I missing, or am I doing this completely wrong?

我错过了什么,还是我这样做完全错误?

采纳答案by CrazyCoder

You have 2 options here:

您在这里有 2 个选择:

  • extract the dependency into the artifact jar so that the app is the single executable jar with all the dependencies
  • link the dependent jars via the Manifest.MFand copy them near the application main jar
  • 将依赖项提取到工件 jar 中,以便应用程序是具有所有依赖项的单个可执行 jar
  • 通过 链接依赖的 jarManifest.MF并将它们复制到应用程序主 jar 附近

I've prepared a sample project that demonstrates both approaches: HelloWithDependencies.zip.

我准备了一个演示这两种方法的示例项目:HelloWithDependencies.zip

The artifacts are produced into out\singleand out\linkeddirectories.

工件生成到out\singleout\linked目录中。

Relevant configurations:

相关配置:

single

单身的

linked

链接

回答by GauravJ

If you are using maven to build your application then this is not the correct way to add external library. You should either

如果您使用 maven 构建您的应用程序,那么这不是添加外部库的正确方法。你应该

  1. Do an install of your library like below mvn install:install-file -Dfile=myJar.jar -DgroupId=com.yourproject -DartifactId=yourproject -Dversion={version} -Dpackaging=jar.
  2. Use system path like explained here.
  1. 像下面一样安装你的库mvn install:install-file -Dfile=myJar.jar -DgroupId=com.yourproject -DartifactId=yourproject -Dversion={version} -Dpackaging=jar
  2. 使用系统路径,如解释here

Option 1 is prefered since you don't have to keep jar in your project.

首选选项 1,因为您不必在项目中保留 jar。