Latest Update

BCSL657D Program 2

2. Working with Maven: Creating a Maven Project, Understanding the POM File, Dependency Management and Plugins.

1: Install the Java JDK

Working with Maven is a key skill for managing Java-based projects, particularly in the areas of build automation, dependency management, and project configuration. Below is a guide on creating a Maven project, understanding the POM file, and using dependency management and plugins:

Overview of the Project

2: Creating a Maven Project

There are a few ways to create a Maven project, such as using the command line, IDEs like IntelliJ IDEA or Eclipse, or generating it via an archetype.

  1. Using Command Line:
    • To create a basic Maven project using the command line, you can use the following command:
mvn archetype:generate -DgroupId=com.example -DartifactId=myapp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
  • groupId: A unique identifier for the group (usually the domain name).
  • artifactId: A unique name for the project artifact (your project).
  • archetypeArtifactId: The template you want to use for the project.
  • DinteractiveMode=false: Disables prompts during project generation.

This will create a basic Maven project with the required directory structure and pom.xml file.

  1. Using IDEs

Most modern IDEs (like IntelliJ IDEA or Eclipse) provide wizards to generate Maven projects. For example, in IntelliJ IDEA:

  1. Go to File > New Project.
  2. Choose Maven from the list of project types.
  3. Provide the groupId and artifactId for your project.

3: Understanding the POM File

The POM (Project Object Model) file is the heart of a Maven project. It is an XML file that contains all the configuration details about the project. Below is an example of a simple POM file:

A basic pom.xml structure looks like this:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>my-project</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!-- Dependencies go here -->
    </dependencies>

    <build>
        <plugins>
            <!-- Plugins go here -->
        </plugins>
    </build>
</project>

Key element in pom.xml:

  • <groupId>: The group or organization that the project belongs to.
  • <artifactId>: The name of the project or artifact.
  • <version>: The version of the project (often follows a format like 1.0-SNAPSHOT).
  • <packaging>: Type of artifact, e.g., jar, war, pom, etc.
  • <dependencies>: A list of dependencies the project requires.
  • <build>: Specifies the build settings, such as plugins to use.

4: Dependency Management

Maven uses the <dependencies> tag in the pom.xml to manage external libraries or dependencies that your project needs. When Maven builds the project, it will automatically download these dependencies from a repository (like Maven Central).

Example of adding a dependency:

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.12.0</version>
    </dependency>
</dependencies>
  • Transitive Dependencies
    • Maven automatically resolves transitive dependencies. For example, if you add a library that depends on other libraries, Maven will also download those.
  • Scopes
    • Dependencies can have different scopes that determine when they are available:
      • compile (default): Available in all build phases.
      • provided: Available during compilation but not at runtime (e.g., a web server container).
      • runtime: Needed only at runtime, not during compilation.
      • test: Required only for testing.

5: Using Plugins

Maven plugins are used to perform tasks during the build lifecycle, such as compiling code, running tests, packaging, and deploying. You can specify plugins within the <build> section of your pom.xml.

  • Adding Plugins
    • You can add a plugin to your pom.xml like so:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

In this example, the maven-compiler-plugin is used to compile Java code and specify the source and target JDK versions.

  1. Common Plugins
    • maven-compiler-plugin: Compiles Java code.
    • maven-surefire-plugin: Runs unit tests.
    • maven-jar-plugin: Packages the project as a JAR file.
    • maven-clean-plugin: Cleans up the target/ directory.
  1. Plugin Goals Each plugin consists of goals, which are specific tasks to be executed. For example:
    • mvn clean install: This will clean the target directory and then install the package in the local repository.
    • mvn compile: This will compile the source code.
    • mvn test: This will run unit tests.

6: Dependency Versions and Repositories

  1. Version Ranges
    • You can specify a version range for dependencies, allowing Maven to choose a compatible version automatically. for example:
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>[30.0,)</version> <!-- Guava version 30.0 or higher -->
</dependency>
  1. Repositories
    • Maven primarily fetches dependencies from Maven Central, but you can also specify custom repositories. For example:
<repositories>
    <repository>
        <id>custom-repo</id>
        <url>https://repo.example.com/maven2</url>
    </repository>
</repositories>

Working with Maven Project

  • Open command prompt.
  • mkdir program2 – this will create program2 folder.
  • cd program2 – navigate program2 folder.
  • After then follow the below step to working with Maven project.

Step 1: Creating a Maven Project

  • You can create a Maven project using the mvn command (or through your IDE, as mentioned earlier). But here, I’ll give you the essential pom.xml and Java code.
  • Let’s use the Apache Commons Lang library as a dependency (which provides utilities for working with strings, numbers, etc.). We will use this in a simple Java program to work with strings.
mvn archetype:generate -DgroupId=com.example -DartifactId=myapp -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
BCSL657D Program 2 CMD

Step 2: Open The pom.xml File

  • You can manually navigate the project folder named call myapp and open the file pom.xml and copy the below code and paste it then save it.
  • In case if you not getting project folder then type command in your cmd.
    • cd myapp – is use to navigate the project folder.
    • notepad pom.xml – is use to open pom file in notepad.
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myapp</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- JUnit Dependency for Testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Maven Surefire Plugin for running tests -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
                <configuration>
                    <redirectTestOutputToFile>false</redirectTestOutputToFile>
                    <useSystemOut>true</useSystemOut>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3: Open Java Code (App.java) File

  • Open a file App.java inside the src/main/java/com/example/ directory.
  • After opening the App.java copy the below code and paste it in that file then save it.
package com.example;

public class App {

    public int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        App app = new App();

        int result = app.add(2, 3);
        System.out.println("2 + 3 = " + result);

        System.out.println("Application executed successfully!");
    }
}

Step 4: Open Java Code (AppTest.java) File

  • Open a file AppTest.java inside the src/test/java/com/example/ directory.
  • After opening the AppTest.java copy the below code and paste it in that file then save it.
package com.example;

import org.junit.Assert;
import org.junit.Test;

public class AppTest {

    @Test
    public void testAdd() {
        App app = new App();
        int result = app.add(2, 3);

        System.out.println("Running test: 2 + 3 = " + result);

        Assert.assertEquals(5, result);
    }
}

Step 4: Building the Project

To build and run this project, follow these steps:

  1. Compile the Project
mvn compile
Compile or build Success CMD
  1. Run the Unit Tests
mvn test
Unit test Success CMD
  1. Package the project into a JAR
mvn package
Package the project into a JAR CMD
  1. Run the application (using JAR)
java -cp target/myapp-1.0-SNAPSHOT.jar com.example.App
Final Output of Program 2

The above command is used to run a Java application from the command line. Here’s a breakdown of each part:

  • java: This is the Java runtime command used to run Java applications.
  • -cp: This stands for classpath, and it specifies the location of the classes and resources that the JVM needs to run the application. In this case, it’s pointing to the JAR file where your compiled classes are stored.
  • target/myapp-1.0-SNAPSHOT.jar: This is the JAR file (Java ARchive) that contains the compiled Java classes and resources. It’s located in the target directory, which Maven creates after you run mvn package.
  • com.example.App: This is the main class that contains the main() method. When you run this command, Java looks for the main() method inside the App class located in the com.example package and executes it.
guest
1 Comment
Inline Feedbacks
View all comments
Sonu
Sonu
14-02-2025 11:06 AM

In Devops lab intelliJ IDEA is used for lab sir?

1
0
Would love your thoughts, please comment.x
()
x