Tuesday, 31 December 2024

What is pom.xml in Maven

 

✅ 1. What is pom.xml in Maven?

  • pom.xml (Project Object Model) is the configuration file for Maven.

  • It defines:

    • Your project details

    • Dependencies (like libraries you use)

    • Build settings

    • Plugins (extra build tools, like making fat JAR)


✅ 2. Maven pom.xml Structure with Explanation

xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mitesh</groupId> <artifactId>myproject</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <!-- ✅ Dependencies: libraries your code needs --> <dependencies> <!-- Example 1: Gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version> </dependency> <!-- Example 2: Apache Commons Lang --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> </dependencies> <!-- ✅ Build section: define plugins and extra build behavior --> <build> <plugins> <!-- Fat JAR Plugin --> <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> <!-- Replace with your actual class --> </manifest> </archive> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>

✅ 3. What Each Section Means

SectionPurpose
<dependencies>Libraries you need (like Gson, Spring, etc.)
<build>Defines plugins and how to build
<plugins>Extra build tools (e.g., for fat JAR)
<mainClass>Entry point (the main() method class)

✅ 4. Maven Commands

TaskCommand
Clean old buildsmvn clean
Compile Java codemvn compile
Create normal JARmvn package
Create fat JAR (with plugin)mvn clean compile assembly:single

🔹 This command will generate:


target/myproject-1.0.0-jar-with-dependencies.jar

✅ 5. Run the Fat JAR


java -jar target/myproject-1.0.0-jar-with-dependencies.jar

This works anywhere — no need to install the 3 dependencies on target machine.


🧪 Sample Java Class

File: src/main/java/com/mitesh/MainApp.java


package com.mitesh; import com.google.gson.Gson; public class MainApp { public static void main(String[] args) { Person p = new Person("Mitesh", 30); String json = new Gson().toJson(p); System.out.println("JSON = " + json); } } class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } }

No comments:

Post a Comment