Contents

All You need to know about Maven

A powerful build automation tool for Java projects

Maven is a powerful build automation tool for Java projects, focusing on dependency management and project lifecycle.

1. Introduction

Maven is a powerful build automation tool for Java projects, focusing on dependency management and project lifecycle. The term “Maven” means “accumulator of knowledge” in Yiddish. It standardizes project builds, manages dependencies, and automates tasks like compiling, testing, packaging, and deploying applications.

Key Features

  • Standard directory structure
  • Automatic dependency management
  • Build lifecycle management
  • Plugin support for various tasks

2. Project Object Model (POM)

The pom.xml file is the heart of every Maven project. It defines project metadata, dependencies, plugins, build profiles, and more.

Basic Structure of pom.xml file

<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-app</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>My App</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <!-- Dependencies go here -->
  </dependencies>
  <build>
    <!-- Plugins and build config -->
  </build>
</project>

Key Elements

  • modelVersion : Version of the POM model.
  • groupId: Unique project group (e.g., com.example). Under a group, you can have multiple projects. Analogy: A folder which can contain multiple files.
  • artifactId: Project name (e.g., my-app). This is the name of the project artifact.
  • version: Project version
  • packaging: Output type (jar, war, etc.) jar is the default packaging type.
  • dependencies: Libraries required by the project
  • build: Plugins and build configuration

3. Archetypes in Maven

Maven archetypes are project templates that help you quickly generate new projects with a predefined structure.

Common Archetypes

  • maven-archetype-quickstart: Basic Java application
  • maven-archetype-webapp: Java web application

Usage

mvn archetype:generate -DgroupId=com.example -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
#where -DgroupId is the group ID, -DartifactId is the project name, and -DarchetypeArtifactId is the archetype to use.

4. Steps to Use Maven for Applications

You can take help from the video tutorial here or follow these overview steps:

  1. Install Maven: Download from Apache Maven and set up environment variables.
  2. Create a Project: Use an archetype to generate a new project.
  3. Write Code: Place source files in src/main/java.
  4. Compile: mvn compile
  5. Test: mvn test
  6. Package: mvn package (creates JAR/WAR)
  7. Run: Use java -cp target/my-app-1.0-SNAPSHOT.jar com.example.Main

Maven Build Lifecycle

Maven defines a build lifecycle that consists of a sequence of phases, each responsible for a specific task in the build process. Each phase can be executed independently or as part of a larger build process.

Maven defines standard lifecycles:

1. Default Lifecycle

The default lifecycle handles the project build process, including compiling code, running tests, packaging, and deploying. They include 23 phases, but the most commonly used ones are:

  • validate: Validate project structure and configuration. E.g: check if pom.xml is valid.
  • compile: Compile source code
  • test: Run unit tests
  • package: Package code (JAR/WAR)
  • verify: Checks if the package is valid and meets quality standards
  • install: Install artifact to local repo
  • deploy: Deploy to remote repo

2. Clean Lifecycle

The clean lifecycle is used to clean up the project by removing files generated during the build process. It includes phases like:

  • pre-clean: Prepare for cleaning
  • clean: Remove previous build files
  • post-clean: Finalize cleaning

3. Site Lifecycle

The site lifecycle is used to generate project documentation and reports. It includes phases like:

  • pre-site: Prepare for site generation
  • site: Generate project documentation
  • post-site: Finalize site generation
  • site-deploy: Deploy generated site to a web server

How to run the lifecycle phases:

mvn [lifecycle-phase]

Example Commands

mvn clean # executes all phases of the clean lifecycle
mvn compile
mvn test
mvn package
mvn install
mvn deploy

Maven Repositories

/posts/maven/Mvn-dependency-flow.png
fig: Maven Repositories flow
Maven uses repositories to manage project dependencies and plugins. Repositories can be local, central, or remote. A Local repository is on your machine, a Central repository is a public repository hosted by Maven, and Remote repositories are custom or company-hosted repositories. When a dependency is declared in the pom.xml, Maven checks the local repository first. If not found, it searches the central repository and then any configured remote repositories as shown in the diagram above. Maven uses repositories to store and retrieve dependencies:

  • Local Repository: This is where MAVEN will keep the downloaded dependencylinux/macOs: home/[user]/.m2/repository and windows: C:\Users\[user]\.m2
  • Central Repository: The default repository for Maven artifacts, hosted by the Apache Software Foundation.
  • Remote Repository: Custom or company-hosted repositories

You can configure additional repositories in your pom.xml or settings.xml.

Configuring Repositories in pom.xml

<project>
  ...
  <repositories>
    <repository>
      <id>central</id>
      <url>https://repo.maven.apache.org/maven2</url>
    </repository>
    <repository>
      <id>my-company-repo</id>
      <url>http://repository.mycompany.com/maven2</url>
    </repository>
  </repositories>
  ...
</project>

Configuring Repositories in settings.xml

The settings.xml file is located in the .m2 directory (e.g., ~/.m2/settings.xml on Linux/macOS or C:\Users\[user]\.m2\settings.xml on Windows). It allows you to configure global settings for Maven, including repositories, mirrors, and proxies.


      <repositories>
        <repository>
          <id>my-company-repo</id>
          <url>http://repository.mycompany.com/maven2</url>
        </repository>
      </repositories>

What is settings.xml?

The settings.xml file is a configuration file for Maven that allows you to customize global settings, such as repository locations, proxy configurations, and user credentials. It is typically located in the .m2 directory in your home folder.


Maven Dependency Management

Declaring Dependencies

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.4</version>
  </dependency>
</dependencies>

Dependency Scopes

Maven supports different dependency scopes to control how dependencies are used in the project. The most common scopes are:

  • compile: Default, available everywhere
  • provided: Needed for compile/test, not packaged
  • runtime: Needed only at runtime
  • test: Only for testing
  • system: Provided by the system, not downloaded

Using scopes helps manage dependencies effectively, ensuring that only necessary libraries are included in the final build. How to use scopes in pom.xml:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.5.4</version>
  <scope>test</scope> <!-- This dependency is only used for testing -->
</dependency>

Transitive Dependencies

Maven automatically includes dependencies of your dependencies. Example: If you depend on spring-boot-starter-web, it will also include spring-web, spring-core, etc.

Excluding Transitive Dependencies

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.5.4</version>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Dependency Management in Multi-Module Projects

In multi-module projects, you can manage dependencies centrally in the parent POM. This allows child modules to inherit versions and configurations. Use <dependencyManagement> in the parent POM to centralize versions.

<project>
  <groupId>com.example</groupId>
  <artifactId>parent-project</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.5.4</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <modules>
    <module>child-module1</module>
    <module>child-module2</module>
  </modules>
</project>

Maven Profiles

Profiles allow you to customize builds for different environments.

Profiles can be activated using the P flag in the command line or by defining conditions in the pom.xml. Profiles can change properties, dependencies, plugins, and more based on the environment (e.g., development, production).

Example of a Maven Profiling

<profiles>
  <profile>
    <id>development</id>
    <properties>
      <db.url>jdbc:h2:mem:devdb</db.url>
    </properties>
  </profile>
  <profile>
    <id>production</id>
    <properties>
      <db.url>jdbc:mysql://prod-server/db</db.url>
    </properties>
  </profile>
</profiles>

Activate with:

mvn clean install -Pdevelopment

Summary

Maven streamlines Java project builds, dependency management, and lifecycle tasks. Mastering its core concepts—POM, lifecycles, repositories, dependency scopes, and profiles—will help you efficiently manage and automate your Java projects.

Additional Resources