Tuesday, 31 December 2024

2 types of JARs in Maven

 

🎯 There are 2 types of JARs in Maven:

JAR TypeWhat it containsNeed dependencies separately?
Normal JAROnly your code (.class files)✅ Yes, dependencies needed on target machine
Fat JAR / Uber JARYour code + all dependencies inside one big JAR❌ No, everything is bundled
                            

🔧 Example: Using Normal JAR

When you run:


mvn clean package

It creates:


target/myproject.jar

But this JAR:

  • Does not include your dependencies (like Gson, Spring Boot, etc.)

  • You will get ClassNotFoundException on the target machine unless:

    • You also copy all 3 dependency JARs

    • Set CLASSPATH or use -cp when running

Example:

bash

java -cp myproject.jar:lib/dependency1.jar:lib/dependency2.jar MainClass

💥 Better Way: Create a Fat JAR

This includes your code + all dependencies, so you only need one JAR to run anywhere.

✅ Add this Maven Plugin to pom.xml

xml
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.3.0</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.mitesh.MainApp</mainClass> <!-- change to your main class --> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build>

🔨 Then run:

bash

mvn clean package

You’ll get a file like:

bash

target/myproject-jar-with-dependencies.jar

Now just copy this one JAR to any machine and run:

bash

java -jar myproject-jar-with-dependencies.jar

✅ Summary

SituationYou Need on Target Machine
Built normal JAR with mvn package❗ All 3 dependencies separately
Built fat JAR with jar-with-dependencies✅ Just 1 JAR (includes everything)

No comments:

Post a Comment