Maven

 
/**
 * MAVEN BUILD - HELLO WORLD EXAMPLE
 * ---------------------------------
 * This is a simple Java application build using Maven.
 * 
 * PURPOSE:
 * -------
 *  - Demonstrate how Maven manages external dependencies.
 *  - Show that third-party libraries can be used WITHOUT 
 *    manually downloading JAR files.
 * 
 * KEY CONCEPTS:
 * -------------
 *  - pom.xml defines project metadata and dependencies
 *  - Maven download required libraries automatically
 * 
 * KEY MAVEN COMMANDS:
 * -------------------
 * mvn compile
 *  - Compiles the source code
 *  - Downloads required dependencies (if not already present)
 *  - Places compiled .class files in target/classes
 *  - Does not create a JAR
 * 
 * mvn exec:java
 *  - Runs the application using Maven
 *  - Automatically builds the runtime classpath
 *  - Includes all project dependencies
 *  - Does NOT require a runnable (fat) JAR
 * 
 * IMPORTANT:
 * ----------
 * mvn exec:java runs the application through Maven,
 * NOT through 'java -jar'.
 * 
 * In this example:
 *  - Joda-Time is an external library
 *  - Maven resolves it and adds it to the classpath 
 */

package demo;

import org.joda.time.LocalTime;

public class HelloWorld {
    public static void main(String[] args) {

        LocalTime currentTime = new LocalTime();

        System.out.println("The current local time: " + currentTime);
            // The current local time: 13:39:34.973
    }
}

Pom

 
<?xml version="1.0" encoding="UTF-8"?>
<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
           https://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>demo</groupId>
    <artifactId>hello-maven</artifactId>
    <version>1.0</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.12.5</version>
        </dependency>
    </dependencies>

    <build>
    <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <mainClass>demo.HelloWorld</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Run

 
mvn exec:java

M2 repository

 
/home/catalin/.m2






Questions and answers:
Clink on Option to Answer




1. Build .jar file with Maven

  • a) mvn compile
  • b) mvn package


References: