Skip to content

Apache Maven for Complete Beginners

Here is a 2800+ word beginner‘s guide to Apache Maven:

Maven is one of the most popular build automation and project management tools used by Java developers. But for beginners, Maven can seem intimidating.

This comprehensive, 2800+ word guide aims to introduce Apache Maven to complete beginners in a simple, easy-to-understand way.

We‘ll start from the basics and slowly build up from there. My goal is to make you comfortable with Maven by the end of this guide. Let‘s get started!

What Exactly is Apache Maven?

Apache Maven is a software project management and build automation tool. It handles the project build, reporting and documentation from a central piece of information – the POM file.

In simple terms, Maven allows you to:

  • Build Java-based projects easily without messy scripts
  • Manage project dependencies from public and private repositories
  • Automate testing, reporting, packaging and deployment of projects
  • Standardize your project build infrastructure for uniformity across software projects

Maven provides structure and consistency – its build lifecycle and conventions remove the guesswork from the build process. Maven emphasizes convention over configuration.

Why Use Apache Maven?

Here are some of the main reasons why developers use Maven:

  • Simplifies build process with standards and conventions
  • Declarative build management through POM file
  • Handles dependencies and libraries smoothly
  • Good integration for testing and reporting
  • Strong community practices built around Maven

In a large enterprise, Maven improves productivity by standardizing and streamlining the project build infrastructure. Developers don‘t waste time figuring out builds – they leverage Maven standards.

Now that you know what Maven is, let‘s look at how Maven structures software projects.

Understanding the Maven Project Structure

Maven emphasizes a standardized project structure for Java-based projects:

my-app
|-- pom.xml
`-- src
    |-- main
    |   `-- java
    |       `-- com
    |           `-- mycompany
    |               `-- app
    |                   `-- App.java
    `-- test
        `-- java
            `-- com
                `-- mycompany
                    `-- app
                        `-- AppTest.java

This layout is prescribed by Maven convention. When you create a Maven project, this initial skeleton structure is created for you.

Let‘s understand what each of these directories and files represent:

  • pom.xml – This is the Project Object Model (POM) file which contains details about your project and configuration details used by Maven to build the project.
  • src/main/java – The location where all your application Java source code lives.
  • src/test/java – The location containing test code and supporting test files.

Easy enough right? This standardized layout removes the confusion around project structure. Now let‘s talk about builds and lifecycles in Maven.

Understanding Maven Builds and Build Lifecycle

The Maven build lifecycle handles the different stages/phases to build, test and deploy your project.

When you execute Maven on a project, it checks the pom.xml for configuration and then executes a series of steps called lifecycle phases to build the project – compile code, package, test and so on.

Here is a visual representation of the Maven Build Lifecycle:

Some key phases you should be familiar with:

  • validate – validate the project
  • compile – compile source code
  • test – test compiled code
  • package – package compiled code into a distributable format like JAR, WAR
  • integration-test – process and deploy the package for testing
  • deploy – copies final package to the production environment

When you execute Maven, it checks the pom and runs through all these lifecycle phases in order unless told otherwise.

Each of these build lifecycle phases consist of plugin goals that enable the functionality for that particular phase. We‘ll get into plugins later. First, let‘s talk about the POM file.

Diving Into the POM File

As noted earlier, POM stands for Project Object Model. It is an XML file (pom.xml) residing in your project‘s base directory.

The POM contains details about your project – its name, version, dependencies etc. along with build profiles, plugins and other configurations required by Maven to build your project.

When you execute Maven, the very first thing it does it check the project‘s pom file.

Here is a simple example pom file:

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0</version>

<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies>

</project>

Here are some key elements:

  • modelVersion – Maven model version
  • groupId – Group or organization identifier
  • artifactId – Name of the project
  • version – Software version of the project
  • dependencies – External libraries/APIs required by the project are listed here

There are a lot more elements but these are most essential for beginners. The POM is the "source of truth" for your project configuration in Maven. Now let‘s talk about dependency management.

Dependency Management using Maven Repositories

One extremely powerful feature of Maven is its automatic dependency management using repositories. But what is a repository and how does this work?

A repository in Maven refers to a directory location from where Maven loads dependencies (JARs/libraries) for your project.

There are three types of repositories defined in Maven:

  • Local Repository – this is a folder location on your local machine where libraries downloaded by Maven are stored for use in other projects. Default is ~/.m2 folder.
  • Central Repository – This is the default public repository provided by Maven community from where libraries are downloaded from.
  • Remote Repository – This could refer to a custom internal repository maintained by your organization containing internal libraries or dependencies.

When you compile a Maven project, here is how the dependency mechanism works:

  • Maven checks project POM file for dependencies listed under element
  • For each dependency, it first checks the local repository on machine
  • If library not available locally, Maven reaches out to central repository to download JAR files
  • The libraries are then copied over to the local repository before being used in project for compilation.

This kind of automated dependency management mechanism makes it very easy to share libraries across projects and teams without messing around with manual installs.

Now that you have a high-level conceptual understanding of Maven, let‘s get our hands dirty and install Maven to try it out.

Installing and Configuring Apache Maven

Installing Maven is a simple 3 step process:

Step 1 – Verify Java JDK is installed

Since Maven produces Java applications, Java JDK v1.7 or above is required.

Step 2 – Download latest Maven version

Head to the official Apache Maven site and download the latest stable release. At time of writing this is Version 3.8.6.

Step 3 – Unzip and configure environment variables

Unzip the downloaded file to your drive location. For e.g C:\ProgramFiles\Apache Software Foundation\apache-maven-3.8.6

Configure Maven home (M2_HOME) and path (%M2_HOME%\bin) variables to point to the Maven and bin folder locations respectively.

Here is a short 1-minute video demonstrating the Maven install and verify process:

And we are done! Maven is now ready to use.

Let‘s create a simple project to test the Maven installation.

Create Your First Maven Project

Use the Maven archetype plugin to bootstrap your first project.

An archetype is essentially a template or model that creates your project and package structure. It‘s a simple way to create a working skeleton.

Here is the archetype plugin command you can execute on the terminal/command prompt:

mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

This will create a starter Java project with Maven‘s default directory structure which we discussed earlier.

Give it a try!

Some Key Maven Concepts Recap

Now that you‘ve created your first project, let‘s recap some of the key concepts we covered so far:

  • POM – The Project Object Model XML file with project configuration details
  • Build Lifecycle – The standardized build pipeline consisting of phases like compile, test, package etc.
  • Dependencies – External libraries required by your code listed in POM file
  • Plugins – Maven addons that execute build lifecycle goals & tasks
  • Archetypes – Project templates to help bootstrap projects consistently

Using Maven Plugins

Plugins and goals provide the actual functionality for executing each build lifecycle phase. We briefly discussed this earlier.

For example, the maven-compiler-plugin is used to compile Java source code during the compile phase. The surefire plugin runs unit test cases during test phase.

Here are some commonly used built-in Apache Maven plugins:

  • clean – cleans the output of project
  • compiler – compiles Java sources
  • surefire – runs unit tests
  • failsafe – runs integration tests

Plugins provide the tools for actual execution. Most plugins are configured automatically, but you can customize plugin executions too.

I‘ve covered the key concepts. Now let‘s move on to the final piece – best practices for organizing your project.

Structuring and Organizing your Maven Project

Here are some best practices you can apply when organizing a Maven project:

  • Follow standard directory conventions of src/main and src/test
  • Create separate sub-modules for specialized functionality using multi-module project approach
  • Place external library JARs under /lib folder
  • Use established naming conventions for project coordinates – groupId, artifactId, version
  • Componentize using packaging options – JAR, WAR, EAR etc.

The project directory structure would look something like:

my-app
|-- pom.xml
`-- src
|-- main
|   |-- java
|   |-- resources
|   `-- lib       
`-- test
    |-- java
    `-- resources

This covers best practices for structuring your project.

Some developers also follow naming conventions like app-core, app-web, app-service to identify different submodules.

I‘ll wrap up this monster guide with some closing thoughts!

Summary

We‘ve covered a lot of ground trying to demystify Apache Maven for beginners.

Here are the key takeaways:

  • Maven handles project build, test and deployment in a structured fashion through an easy to use lifecycle mechanism.
  • The declarative Project Object Model approach promotes reuse and consistency
  • Standardization and convention over configuration removes guesswork
  • Automated dependency management system is extremely powerful
  • Plugins provide the tools and integrations to execute the build process seamlessly

Maven lowers barriers to usage through standards and sensible conventions. These best practices leverage collective community wisdom.

I hope you‘ve enjoyed this detailed beginner‘s guide. Please leave comments if you have any other questions!

Happy Learning!