Intellij Java 2016 & Maven: how to embed dependencies in JAR?

I use Intellij Java 2016.2.2 and Maven to create a very simple Java console application.

I want to add an external library, so I add my dependency to Maven as follows:

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

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

I checked, and for some reason, the external JAR is not added to the JAR that I just generated. I also tried a lot of things in โ€œFile โ†’ Project Structureโ€, but still not working ...

I just want to create a JAR with my dependencies, so I can just run my application in the console using:

 java -jar myproject.jar 

How can i do this? Thank you for your help!

+5
source share
2 answers

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

  • add dependencies in pom.xml file
  • go to File โ†’ Project Structure โ†’ Artifacts โ†’ Create โ†’ JAR โ†’ From a module with dependencies
  • select Primary class and click OK
  • in your project, in src / main, create the "resources" folder
  • move the "META-INF" folder (with the MANIFEST.MF file in it) in this "Resources" folder
  • go to build โ†’ build artifacts to build the JAR

EDIT

It is better (and easier) to do this by adding the following lines to 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> 

then use the clean and batch maven commands.

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

+13
source

Well, thatโ€™s why you basically want to create a โ€œthick jarโ€ (sometimes called an assembly) that contains all its dependencies (usually external dependencies are external). A.

For this you need to use the Maven plugin. The following is an example configuration of the jar-with-dependencies build assembly plugin:

 <project> ... <build> ... <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.6</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> ... </project> 

then just run

 mvn package 
+4
source

All Articles