Maven for Java Developers: A Step-by-Step Guide to Setting Up and Building Projects
Hands-on Maven: From Basic Setup to Building Core Java Projects
What is Maven?
Maven is a build and dependency management tool for software projects.
It’s a tool to define how a project is built and how it’s dependencies are managed in order to build the project artifacts i.e JAR, WAR or EAR of a Java project.
Key Features and Benefits:
- Standardized build process: Provides a uniform build system, simplifying project builds and dependency management.
- Project templates (archetypes): Allows quick setup of standard project structures.
- Dependency management: Automates the process of downloading and integrating project dependencies.
Setting Up Maven
Prerequisites for Installing Maven
Before installing Maven, ensure that Java JDK is installed and the JAVA_HOME environment variable is set.
You can download Maven from the website at https://maven.apache.org/. You can click at the Download section on top left and then click on the Link for beside Binary zip archive under Files section as shown in the image below .
Installing Maven on Windows
Extract the Maven ZIP file to a desired location. For e.g. I have extracted the download zip file apache-maven-3.9.5-bin.zip in the location (D:\Maven_Setup\apache-maven-3.9.5) like the image shown .
Set up MAVEN_HOME environment variables pointing to your Maven folder.For this ,type environment variables in windows search in your taskbar and click on Environment variables.
After clicking on Environment Variables and click on New in System Variables. For variable name, give MAVEN_HOME, and for value, give location of folder where maven extraction is done.
Adding of new environment variable MAVEN_HOME
Then select the Path variable in System Variables and click Edit.
At the end of your Path System Variable add “;%MAVEN_HOME%\bin”. To allow Maven commands to be run from any directory are doing this .Please note, the semicolon (;) is a delimiter that in turn allows the system to distinguish different paths from one another
Editing the system variable PATH
Verifying Maven Installation
mvn -version or
mvn -v in your command line to verify the installation.
Creating a simple project with Maven
Let’s start creating the first simple project using Maven, by performing the following steps:
- Open a command prompt and change the directory to the folder in which you want to create your first Maven project. Run the following command:
mvn archetype:generate -DgroupId=org.lfs.mavenlearning -DartifactId=mavenlearning -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
The groupId is a unique identifier for your project and is usually structured like a reverse domain name. The artifactId is the name of the project and is often the name of the project’s base directory and the generated JAR file.
You can change the groupId and artifactId values in the preceding command as per your requirement.
Let’s break down this command:
- mvn archetype:generate: This is a Maven command to generate a new project from an archetype. Archetypes are templates for creating projects with a predefined structure.
- -DgroupId=org.lfs.mavenlearning: The groupId is a unique identifier for your project and is usually structured like a reverse domain name. In this case, org.lfs.mavenlearning is the groupId.
- -DartifactId=mavenlearning: The artifactId is the name of the project. It’s often the name of the project’s base directory and the generated JAR file. Here, mavenlearning is the artifactId.
- -DarchetypeArtifactId=maven-archetype-quickstart: This specifies the archetype to use. The maven-archetype-quickstart is a simple archetype for creating a Java application.
- -DinteractiveMode=false: This disables the interactive mode, meaning Maven won’t ask for input during project generation. It will use the provided parameters instead.
2. Once the above command is fired , you will see Maven downloading a bunch of files:
3. Then it will start generating sources:
4. Once Maven has completed generating sources, it will create the project that we want
Exploring Maven Folder Structure
The Folder Structure of the Maven Project we just created looks like the image below .Here ,the project folder mavenlearning is created with two things
- src directory — it is the root for our application source code and tests
- pom.xml — the Maven configuration file
Inside the src folder ,we have the following sub folders:
A bunch of folders are created over here :
- src\main\java: This is for Java source files
- src\test\java: This is for Java test source files
- Within each of the preceding folders, a package structure corresponding to the groupId (org.lfs.mavenlearning) is created
Two sample classes, namely App.java and AppTest.java, are also created at the location src\main\java\org\lfs\mavenlearning and src\test\java\org\lfs\mavenlearning respectively. The App.java class is the entry point for the application, and the AppTest.java class contains unit tests for the application.
Open the generated Java class,
App.java. The content would look like the following:
* Hello world!
public class App
public static void main( String args )
System.out.println( "Hello World!" );
Building project with Maven
To build the previously created simple project with Maven, perform the following steps:
- Open the command prompt and run the following command, changing the directory to the folder the project was created:
mvn clean package
2. Observe the following things in the output:
Note: If this is your first time running Maven, it will download the plugins and dependencies required for it to run. Thus, your first build might take longer than you would expect.
It would create a new folder named target under the project root directory .
The target folder holds generated artifacts such as the mavenlearning-1.0-SNAPSHOT.jar in this case along with many other directories .The mvn package command packages the project into a JAR file. The target folder contains the generated JAR file, as well as other artifacts such as class files and documentation.
Run Your Program Execute the following command to run the App.java code from mavenlearning-1.0-SNAPSHOT.jar file:
java -cp target/mavenlearning-1.0-SNAPSHOT.jar org.lfs.mavenlearning.App
The console output would look like the following:
Understand the important Maven concepts
In order to use Maven successfully and understand how it works we need to focus on the following topics first
- POM file (pom.xml)
- Build Life Cycles, Phases,Plugins and Goals
Understanding POM file (pom.xml)
Every Maven project has a pom.xml file,it is the Project Object Model (POM), a declarative description of a project. The
pom.xml file defines how Maven should build and manage your project.When Maven executes a goal, each goal has access to the information defined in a project’s POM. Let’s go through pom.xml which got created in the project mavenlearning.
The over all content is provided below:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- Project Root:
<project>is the root element. It includes namespaces and schema locations that are standard for a Maven POM file.
- Model Version:
<modelVersion>4.0.0</modelVersion>specifies the model version of Maven being used. This is mandatory for any POM file.
- Project co-ordinates: Project co-ordinates are the minimal basic fields that a POM definition must contain. The three co-ordinate fields are groupId, artifactId, and version.In the above file the groupId i.e.
groupId>org.lfs.mavenlearning</groupId>uniquely identifies your the project across all projects whereas artifactId i.e.
<artifactId>mavenlearning</artifactId>is the name of the jar without version. If you created a jar, it would be named
<version>1.0-SNAPSHOT</version>is the version of the artifact generated by the project.
<packaging>jar</packaging>defines the packaging type of the project. Here, it's a JAR.
<name>mavenlearning</name>is a human-readable name of the project.
<url>http://maven.apache.org</url>provides the location where your project's site can be found.
- Dependencies: The
<dependencies>section is where you define the dependencies needed for your project. Dependencies are external Java libraries that your project needs to compile and run.
In your specific
pom.xml, there is one dependency defined:
- JUnit Dependency:
<groupId>junit</groupId>: The group ID for JUnit, the unit testing framework.
<artifactId>junit</artifactId>: The artifact ID for JUnit.
<version>3.8.1</version>: This specifies the version of JUnit.
<scope>test</scope>: This defines the scope of the dependency. Here, 'test' indicates that JUnit is not required for normal use of the application; it's only needed for testing purposes.
You specify in the POM file what external libraries your project depends on, and which version, and then Maven downloads them for you and puts them in your local Maven repository. If any of these external libraries need other libraries, then these other libraries are also downloaded into your local Maven repository.In this case ,when Maven processes the POM file, it will download JUnit version 3.8.1 for use in testing phases but will not include it in the final packaged JAR. This approach helps manage project dependencies efficiently, ensuring that only necessary libraries are packaged with your software.
Maven Build Life Cycles, Phases,Plugins and Goals
Maven Goals — units of work
A Maven goal is a specific task that may be executed as a standalone goal or along with other goals as part of a larger build. A goal is a “unit of work” in Maven.
Goals can be executed from the command line using the mvn command followed by the goal name.Examples of common Maven goals include compile, test, package, and install.
A Maven Plugin is a collection of one or more goals. Plugins are the building blocks of Maven’s functionality.Maven has a vast ecosystem of plugins that cover a wide range of tasks and integrations.Examples of popular Maven plugins include the Maven Compiler Plugin, Surefire Plugin for testing, and the Maven Assembly Plugin for creating custom distributions.
A plugin is a collection of goals also called MOJO (Maven Old Java Object).
A plugin is like a class and goals are methods within the class.
Examples of goals include the compile goal in the Compiler plugin, which compiles all of the source code for a project, or the test goal of the Surefire plugin, which can execute unit tests.
Let’s check our old example again.
mvn archetype:generate -DgroupId=org.lfs.mavenlearning -DartifactId=mavenlearning -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Here,we passed in the configuration parameters groupId and artifactId to the generate goal of the Archetype plugin via the commandline parameters -DgroupId=org.lfs.mavenlearning and -DartifactId=mavenlearning.
Note When referring to a plugin goal, we frequently use the shorthand notation: pluginId:goalId. For example, when referring to the generate goal in the Archetype plugin, we did use archetype:generate.
The core of Maven has little to do with the specific tasks involved in your project’s build. By itself, Maven doesn’t know how to compile your code or even how to make a JAR file. It delegates all of this work to Maven plugins like the Compiler plugin and the Jar plugin, which are downloaded on an as-needed basis and periodically updated from the central Maven repository. When you download Maven, you are getting the core of Maven, which consists of a very basic shell that knows only how to parse the command line, manage a classpath, parse a POM file, and download Maven plugins as needed.
Maven Lifecycle and Phases
As we already know ,Maven goals are granular and typically perform one task. Multiple goals need to be executed in an orderly fashion to perform complex operations such as generating artifacts or documentation. Maven simplifies these complex operations via lifecycle and phase abstractions such that build related operations could be completed with a handful of command.
Maven’s build lifecycle constitutes a series of stages that get executed in the same order. Maven refers to these stages in a lifecycle as phases. Every Maven project has the following three built-in lifecycles:
- default: This lifecycle handles the compiling, packaging, and deployment of a Maven project.
- clean: This lifecycle handles the deletion of temporary files and generated artifacts from the target directory.
- site: : This lifecycle handles the generation of documentation and site generation.
To better understand the build lifecycle and its phases, let’s look at some of the phases associated with the default lifecycle:
- validate: Runs checks to ensure that the project is correct and that all dependencies are downloaded and available.
- compile: Compiles the source code.
- test: : Runs unit tests using frameworks. This step doesn’t require that the application be packaged.
- package: Packages the compiled code into a distributable format, such as JAR or WAR.
- install: : Installs the packaged archive into a local repository. The archive is now available for use by any project running on that machine.
- deploy: Pushes the built archive into a remote repository for use by other teams and team members.
The build phases are executed sequentially. When we run a maven build command, we specify the phase to be executed. Any maven build phases that come before the specified phase is also executed. This means that if we run a specific phase using the command:
mvn <Phase Name>
It won’t only execute the specified phase, but all the preceding phases as well.For example, if we run
mvn package then it will execute validate, compile, test, and package phases of the project.Similarly if we run
mvn deploy, which is the last phase in the default build lifecycle, it’ll execute all the phases before the deploy phase as well, which is the entire default lifecycle.
Maven lifecycle is an abstract concept and can’t be directly executed. Instead, you execute one or more phases. So for example, the command mvn package will execute the package phase of the default lifecycle. In addition to clearly defining the ordering of phases in a lifecycle, Maven also automatically executes all the phases prior to a requested phase. So, when the mvn package command is run, Maven will run all prior phases such as compile and test. A number of tasks need to be performed in each phase. For that to happen, each phase is associated with zero or more goals. The phase simply delegates those tasks to its associated goals. Following diagram shows the association between lifecycle, phases, goals, and plugins:
Watch the Tutorial: Maven Quick Start By Example
To complement the written guide, I’ve prepared a Maven Quick Start By Example video tutorial on YouTube !
The tutorial covers the essentials of Maven usage. If you enjoy the video and are looking for more content on software development, don’t forget to subscribe to my YouTube channel for regular updates.
In this article, we’ve navigated the essentials of Maven, highlighting its role in simplifying Java project builds and dependency management. From setting up Maven and understanding its core concepts to creating a project and exploring its structured folder layout, we’ve laid a foundation for efficient Java development. As you apply these principles in your projects, Maven will prove to be an invaluable tool, enhancing organization, consistency, and productivity in your Java development journey.
Thanks for reading!! If you have enjoyed it, please Clap & Share it!!
If you found this article valuable and would like to read more of my work, consider following me on Medium for regular updates.