Apache Maven Tutorial: learn the best Java build automation tool
Tags: java, tutorial, programming
Published: 2023-02-21 19:54:31

Maven is the most popular, de-facto build tool for **Java projects**. But Maven is much more than a build tool. In fact, it can be used to manage an entire project. 

As a budding computer science professional, you will inevitably run into Maven POM files that can be hard to understand without knowing the fundamentals of Maven. 

This tutorial introduces you to Maven concepts like plugins, goals, dependencies, and more.

**Today, we will learn:**
* [What is Maven?](#what-is)
* [Salient features of Maven](#salient) 
* [Maven Plugins](#plugins)
* [Maven POM](#pom)
* [Maven Lifecycle](#lifecycle)
* [Maven Repository](#repository)
* [How to install Maven](#install) 
* [Advanced Maven concepts to learn next](#next)

<a name="what-is"></a>
 
## What is Maven?

A build is a process of converting source code files into software artifacts to run on a computer. This process is usually managed by a **build tool**, a program that controls other programs. 

Maven is the most popular de-facto build and management tool for Java projects. Maven is based on the concept of a **project object model (POM)**, which helps to automatically manage a project's build, documentation, and reporting from a central piece of information. 

Maven has become very popular over the years, and it has defined a common interface for building software. Maven implements plugins that can be retrieved from the Maven repository. 

> Simply put, Maven is a tool for building and managing Java-based projects that make the work of Java developers much easier.

Maven offers support for many tasks, including: 
* Easily build a Java project from scratch and without scripting
* Easily add JARs and project dependencies
* Access project information, such as log documents, unit tests, dependency lists, etc. 
* Update the central repository for JARs and dependencies.
* Integrate a Java project with a control system

<br>

### When to use Maven

The Maven Build Tool is ideal when a project has many dependencies or when project dependency versions update often. It is also well-suited for **continuous builds**, integration, and testing or when you need to generate documentation from your source code.

<br>

### Maven Pros and Cons

**Pros:**
* Maven can automatically add all project dependencies by reading a `pom` file.
* It’s super easy to add a dependency in a `pom` file.
* Maven makes it easy to start a project in different environments without dealing with injection, builds, etc. 

**Cons:**
* Maven must be downloaded with the Maven plugin for an IDE
* Only existing dependencies can be added to a project 

<br>

<a name="salient" ></a>
 
## Salient features of Maven

Now that we know what Maven is and how it works, let’s learn about the most salient features of this build tool. We will break these down in more detail later in the article. 

* **POM Files:** Project Object Model (POM) Files are XML files containing project and configuration information. Maven POM files are used to execute the commands. 
* **Dependencies and Repositories:** Dependencies are external Java libraries, while repositories are the directories for packaged JAR files. Maven repository.
* **Build Plugins:** Build plugins to perform specific goals for your project. These are added to the POM file. Maven provides standard plugins, or you can implement your own. 
* **Life Cycles, Phases, and Goals:** A build life cycle is made up of multiple build phases, which are simply a sequence of project goals. The build lifecycle is named a Maven command.
* **Build Profiles:** Build profiles are a set of configuration values that allow you to build with different configurations. You add build profiles to your POM files using the elements of the profile.

![Maven](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4mvbr7c1xv6k9wj9vbky.png)

<br>

<a name="plugins"></a>
 
## Maven Plugins

Maven can accept various plugins to perform tasks. Since the core of Maven is small, **plugins are essential** to leverage the intelligence of this tool. Plugins are just codes that implement logic to perform various tasks during the build process. 

Some of the most common plugins are:
* **Compiler Plugin:** contains the logic to compile
* **Jar Plugin:** contains the logic to create jars
* **Surefire Plugin:** contains the logic to execute unit tests

A Maven plugin is made of goals that are a unit of work. A goal is an action we want to take on the project defined by a POM file. Take a look at this diagram to understand how these components interact:

![Maven plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s96g9dvc131xsqcyvm8b.png)

<br>

<a name="pom"></a>
 
## Maven POM

A Maven project is described by a POM file (Project Object Model), which is a declarative description of your Java project. The POM is an XML file that defines the project’s unique Maven coordinates, dependencies, required plugins, parameters, etc. 

When invoked, Maven looks for the POM file in the current directory structure. Without it, an error will be thrown. Then, Maven reads the POM, gathers the configuration information, and executes the goal. 

Some of the configurations that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. 

> You can also specify the other information, such as the project version, description, developers, and mailing lists.


Let’s look at a minimal version of a POM file.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.datajek</groupId>
    <artifactId>empty-project</artifactId>
    <version>1</version>
 
</project>
```

The file contains minimal project descriptions without dependencies or plugins. If you run `mvn install` in the directory containing the above POM file, you’ll see a successful build. 

There are several elements we use for creating this file: 
* **project:** the root element of a new project
* **modelVersion** we recommend using version 4.0.0 
* **groupId:** This is the unique id for the project group
* **artifactId:**  this gives a project name
* **version:** this holds the project’s version number 

> Other elements include dependencies, name, scope, and packaging. 

<br>

<a name="lifecycle"></a>

## Maven Lifecycle

Maven supports a build lifecycle, which is an **ordered set of actions** used for building a project. A build life cycle is made up of build phases, and each phase has plugin goals, which are executed when the phase executes.

To understand this better, let’s look at an example.**The clean lifecycle** includes:
* `pre-clean`
* `clean`
* `post-clean`

The phases of a lifecycle execute in order, meaning that `pre-clean` will execute first, `clean` secondly, and finally `post-clean`.  

If we run the clean phase in an EmptyProject using `mvn clean`, we can specify the phase with the `mvn` command. When we execute the `clean` phase, the previous phase will also execute if it has any plugin goals.

<br>

<a name="repository"></a>

## Maven Repository 

A repository in Maven holds both **build artifacts** and **dependencies**. In software development, artifact refers to objects that are produced in the process, like design documents, data models, and workflow diagrams. 

There are two main types of Maven repositories:
* **Local repository:**  the directory where Maven runs and catches remote downloads
* **Remote repositories:** any other type of repository. For example, a repository set up by a third party or an HTTP server within your company.

Generally speaking, local repositories can be left alone except for cleaning. You will need to download remote repositories, which are triggered when declaring a dependency. 

> Maven will download from the central repository by default. 
 
<br>

<a name="install"></a>

## How to install Maven

Downloading Maven is quite easy. Start by verifying that you have Java installed. Check if your Java environment variable is set. From there, download Maven from the official site.

You can unpack the zip from anywhere in your system and add the bin directory to the PATH environment variable and system variable. 

From there, `cmd` and run the `mvm -v` command. A proper installation will print the following lines:

```xml
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-25T01:19:05+05:30)
Maven home: C:\apache-maven-3.5.3\bin\..
Java version: 1.8.0_151, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_151\jre
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
```
 
<br>

<a name="next"></a>

## Advanced Maven concepts to learn next

You should now have a strong idea of what Maven is and how to use it in your Java projects. Maven can make your build process far easier and automate time-consuming tasks. But there is still a lot more that Maven can offer you. 

The **advanced Maven concepts** that you should learn next are:
* Dependency Management and Scopes in Maven
* Plugin Management
* Maven Super POM
* Aggregation in Maven 

To get started with these advanced concepts and get more practice with what we’ve learned today, check out Educative’s course **[Build Java Projects with Maven](https://www.educative.io/courses/build-java-projects-with-maven?eid=5082902844932096)**. This unique course provides easy-to-follow, hands-on, in-browser exercises to teach Maven concepts like plugins, goals, dependencies, and more. 

After these lessons, you’ll be working confidently with Maven in no time!

*Happy learning!*

### Continue reading about Java on Educative
* [5 simple and effective Java techniques for strings and arrays](https://www.educative.io/blog/5-java-techniques-strings-arrays?eid=5082902844932096)
* [Java interview prep: 15 Java interview questions](https://www.educative.io/blog/15-java-interview-questions?eid=5082902844932096)
* [Java Multithreading & Concurrency: Cracking senior interviews](https://www.educative.io/blog/java-multithreading-and-concurrency-what-to-know-for?eid=5082902844932096)

### Start a discussion
Are you a fan of Maven's offerings? Was this article helpful? Let us know in the comments below!