Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding external library to artifact jar in IntelliJ IDEA

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?

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:

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?

like image 268
Shivashriganesh Mahato Avatar asked Feb 13 '17 04:02

Shivashriganesh Mahato


2 Answers

You have 2 options here:

  • 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.MF and copy them near the application main jar

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

The artifacts are produced into out\single and out\linked directories.

Relevant configurations:

single

linked

like image 106
CrazyCoder Avatar answered Oct 21 '22 11:10

CrazyCoder


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

  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.

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

like image 1
GauravJ Avatar answered Oct 21 '22 12:10

GauravJ