Maven Build Life Cycles, Phases and Goals

Apache Maven Tutorial - Build Life Cycle, Phases, and Goals

Maven’s Sequential Execution

In Maven, you have the option of executing a build phase or build goal. But unlike build goals, which can be called and executed individually, Maven follows a sequential or hierarchical order of execution for build phases.

For example, if you run a phase that is at level 5 in the life cycle hierarchy, all preceding phases (i.e., phase 1 to 4) are also executed. This will become clearer with explanations in the subsequent sections.

Let us understand, what do we mean by ‘sequential execution‘ in a more realistic way, by looking at what happens when you execute build phases or build goals:

  • When you execute a build phase, you are in fact executing all build goals within that build phase, as well as all build phases prior to this phase in the hierarchy.
  • In Maven terms, a build goal is a ‘unit of work’. Hence It is possible to execute goals independently (besides being part of a larger work hierarchy). So, when you can execute a specific build goal directly, in this case only the specific build goal (and task inside goal) gets executed.

Maven Build Life Cycles

The Maven build life cycle is divided into ‘Build Phases’. These build phases are further divided into ‘Build Goals‘. [Lifecycle > Phases > Goals]

By default, Maven contains the following three built-in build life cycles:

  • default: Responsible for project deployment (contains 23 phases)
  • clean: Cleans project and removes all files generated by the previous build (contains 3 phases)
  • site: Create the project’s site documentation (contains 4 phases)

Each of these build lifecycles is defined by a different list of build phases, wherein a build phase represents a stage in the lifecycle as shown in the below table:

Clean LifecycleDefault LifecycleSite Lifecycle
Phase Description
pre-clean execute processes needed prior to the actual project cleaning
clean remove all files generated by the previous build
post-clean execute processes needed to finalize the project cleaning
Phase Description
validate validate the project is correct and all necessary information is available
initialize initialize build state, e.g. set properties or create directories
generate-sources generate any source code for inclusion in compilation
process-sources process the source code, for example to filter any values
generate-resources generate resources for inclusion in the package
process-resources copy and process the resources into the destination directory, ready for packaging
compile compile the source code of the projec
process-classes post-process the generated files from compilation, for example to do bytecode enhancement on Java classes
generate-test-sources generate any test source code for inclusion in compilation
process-test-sources process the test source code, for example to filter any values
sgenerate-test-resources create resources for testing
process-test-resources copy and process the resources into the test destination directory
test-compile compile the test source code into the test destination directory
process-test-classes post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes
test run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed
prepare-package perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package
package take the compiled code and package it in its distributable format, such as a JAR
pre-integration-test erform actions required before integration tests are executed. This may involve things such as setting up the required environment
integration-test process and deploy the package if necessary into an environment where integration tests can be run
post-integration-test perform actions required after integration tests have been executed. This may including cleaning up the environment
verify run any checks to verify the package is valid and meets quality criteria
install install the package into the local repository, for use as a dependency in other projects locally
deploy done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects
Phase Description
pre-site execute processes needed prior to the actual project site generation
site generate the project’s site documentation
post-site execute processes needed to finalize the site generation, and to prepare for site deployment
site-deploy deploy the generated site documentation to the specified web server

For a complete listing of Maven’s life cycle and phases refer to the above table.

Executing Maven Life Cycles

It is not possible to execute the ‘default’ build life cycle directly (not permitted). In fact, there is no command for executing any Maven life cycle ‘directly’. Instead, you execute a life cycle by calling single or multiple ‘build phases’ contained inside the lifecycle in such a way that all preceding build phases of the lifecycle automatically get executed (due to the sequential execution nature of Maven) giving you the net result equivalent to full life cycle execution.

For a more concrete example, consider the Maven’s default life cycle phases as mentioned below in the section Build Phases for Default Life Cycle, and suppose you want to execute the entire default life cycle. if you executed ‘deploy’ phase of the default Maven lifecycle by calling –

mvn deploy

The above command would execute each default lifecycle phase in the order (validate > compile > test > package > integration-test > verify > install), before executing ‘deploy’ phase itself.

  • Validate Phase
  • Compile Phase
  • Test Phase
  • Package Phase
  • Integration-test Phase
  • Verify Phase
  • Install Phase
  • Deploy Phase

Note: The above list only shows some of the main phases. There are however more phases involved but not shown here. For a complete list refer to ‘Default Life Cycle‘ in the above section.

Hence you only need to call the last build phase to be executed, (which is the ‘deploy’ phase in this case), and doing so, automatically executes preceding phases.

As mentioned, though it is not possible to execute the ‘default’ life cycle directly, you can however execute a specific build phase within the default build life cycle to achieve your objective as shown in the above example wherein we executed the ‘deploy’ build phase of the default Maven’s default life cycle.

All the phases contained in the default life cycle, clean life cycle, and site life cycle have been explained in the below section.

Maven Build Phases

A Maven build phase represents a stage in the Maven build lifecycle. Each phase is responsible for a specific task. Usually, a Maven life cycle would contain multiple phases.

You can execute a build phase located inside a build life cycle by passing the name of the build phase to the Maven command. Maven would evaluate what build life cycle the specified build phase belongs to, hence you don’t need to explicitly specify which build life cycle.

Here are some build phase commands:

mvn compile
mvn package

Build Phases for Default Life Cycle

The default Maven lifecycle consists of the following main 8 phases (out of total 23 phases) for the building project. These lifecycle phases are executed sequentially as explained in the earlier section

  • Validate: This phase validates if the project structure is correct. It also makes sure that all dependencies have been downloaded and are available in the local repository.
  • Compile: As the name suggests, it compiles the source code stores the compiled classes in the target/classes folder.
  • Test: This phase runs the unit tests against compiled source code using a suitable unit testing framework if available.
  • Package: This phase packages the compiled code in a distributable format like JAR or WAR.
  • Integration-test: This phase takes the packaged result and executes additional tests such as integration tests for the project.
  • Verify: This phase performs checks to verify to make sure the project is valid and meets the quality standards.
  • Install: This phase installs the packaged code (result of package phase) to the local Maven repository.
  • Deploy: This phase deploys/copies the packaged code to target, e.g a remote repository.

Here are some build phase commands for Maven’s Default Life Cycle:

mvn verify
mvn compile

Build Phases for Clean Life Cycle

Maven’s ‘clean’ life cycle contains the following phases as shown in the below table:

Phase Description
pre-clean execute processes needed prior to the actual project cleaning
clean remove all files generated by the previous build
post-clean execute processes needed to finalize the project cleaning

Here are examples for executing Maven’s Clean Life Cycle phases:

mvn clean
mvn post-clean (not recommended)
Note: It is not recommended to execute some phases on their own (independently) on command line since such phases are ‘intermediary’ steps and may yield undesirable results if executed independently. Read more on the section ‘Avoid Calling Intermediary Phases’

Build Phases for Site Life Cycle

Maven’s ‘site’ life cycle contains the following phases as shown in the below table:

Phase Description
pre-site execute processes needed prior to the actual project site generation
site generate the project’s site documentation
post-site execute processes needed to finalize the site generation, and to prepare for site deployment
site-deploy deploy the generated site documentation to the specified web server

Here are examples for executing Maven’s Site Life Cycle phases:

mvn site
mvn pre-site (not recommended)
Note: It is not recommended to execute some phases on their own (independently) on command line since such phases are ‘intermediary’ steps and may yield undesirable results if executed independently. Read more on the section ‘Avoid Calling Intermediary Phases’

Avoid Calling Intermediary Phases

Please note that there are some special ‘sort of’ phases that are not recommended to be called directly from the Maven command line.

The phases named with hyphenated words (pre-, post-, or process-*) are not usually directly called from the command line. Such ‘phases’, sequence the build, producing intermediate results that are not useful outside the build.

Maven Build Goal

As mentioned earlier, a ‘Build Phase’ is made up of one or more ‘Plugin Goals’, where a ‘plugin goal’ represents a specific task that contributes to the building and managing of a project. It may be bound to zero or more build phases. If a goal is bound to one or more build phases, that goal will be called in all those phases.

Maven goals can also be run independently or else they get executed as part of the build phase if attached to a build phase.

Also, note that unlike ‘build phases’ the ‘build goal’ doesn’t have the concept of ‘sequential execution’ since they are individual and independent ‘unit of work’ or ‘task’.

Note: A goal not bound to any build phase could be executed outside of the build lifecycle by direct invocation. However, if a build phase has no goals bound to it, that build phase will not execute.

Executing Maven Build Goals

The syntax for running a specific goal, without executing its entire phase and the preceding phases is:

mvn <Plugin_Name>:<Goal_Name>

Here are two examples for executing Maven Goals independently of the build phase or life cycle:

compiler:compile – Executes the compile goal from compiler plugin
compiler:testCompile - Executes testcompile goal from compiler plugin.
surefire:test - Executes test goal from the surefire plugin

TIP: You can list all goals bound to a specific phase and their plugins using command. For example, to list all goals bound to the ‘verify’ phase, we can run: mvn help:describe -Dcmd=verify

Adding Goals to Phases

While customizing your Maven project, you may often require assigning new tasks to build phases, in other words adding new goals to build phases or even adding independent goals. You can generally achieve this easily via packaging and plugins. These are explained briefly in the subsequent sections.

Maven Project Packaging

This is perhaps the most common and easy way for defining ‘Goals’ (tasks). You can set the packaging for your project via the POM element called <packaging>.  Based on the defined ‘packaging’ a specific set of goals bind to a particular phase.

For example, the jar packaging will bind the following goals to build phases of the default lifecycle.

Phase plugin:goal
process-resources resources:resources
compile compiler:compile
process-test-resources resources:testResources
test-compile compiler:testCompile
test surefire:test
package jar:jar
install install:install
deploy deploy:deploy

Some of the valid packaging values are jar, war, ear and pom. If no packaging value has been specified, it will default to jar. You can refer to more details about packaging and their default bindings here – https://maven.apache.org/ref/3.8.5/maven-core/default-bindings.html

Maven Plugins

Maven Plugins are artifacts that provide ‘Goals’ to Maven, in other words, Maven plugins define one or more goals that represent the functionality or capability of that plugin. For example, the Compiler plugin has two goals: compile and testCompile.

Also, a plugin may define a set of goals that may not necessarily all bound to the same phase but rather could be distributed or used across phases.

TIP: You can use the following command to list all goals in a specific plugin. For example, to list all goals in the ‘compiler’ plugin, use the following command: mvn compiler:help

Depending on your requirement, you can either choose to use an existing plugin from the Maven repository or you can write your own custom plugin as well. Here is an example of typical <plugin> configuration in pom.xml

    <plugins>
        <plugin>
            <groupId>com.adojos</groupId>
            <artifactId>my-custom-maven-plugin</artifactId>
            <version>0.0.1-SNAPSHOT</version>
            <executions>
                <execution>
                    <goals>
                        <goal>my-custom-goal</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <scope>test</scope>
            </configuration>
        </plugin>
    </plugins>
Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary JAR files, compiling the source...

Maven CLI Options and Switches Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

How To Create Maven Project in Eclipse With Archetype

Maven Basics Maven automates the steps involved in building a software application like adding the JAR files, compiling code, running unit tests, creating the output...

How To Create Maven Project in Eclipse Without Archetype

Maven is a very popular build and dependency management tool. Eclipse is an IDE that helps developers write and run Java code easily. In...

How To Create Maven Project Using Command Line

Maven project can be easily created using built-in plugins from the popular IDEs such as Eclipse and IntelliJ IDEA. However, in scenarios where you...
- Advertisement -spot_img

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

Â

MORE ON CODEX

RECENT PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows. Demonstrating the capability...

MORE IN THIS CATEGORY

How To Create Maven Project Using Command Line

Maven project can be easily created using built-in plugins from the popular IDEs such as Eclipse and IntelliJ IDEA. However, in scenarios where you...

Convert List to Array Using ToArray With Param

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array that is of the same...

How To Remove Duplicates From List in Java

Introduction A List is an interface in the Java collection framework which can be used to store a group of objects. A List is ordered...

Does VBScript Supports all COM Objects ?

Well the answer in one line is - No VBScript does not supports all COM Objects or Servers! VBScript works with only a subset of ‘Objects’...

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...

CHECKOUT TUTORIALS

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...
- Advertisement -spot_img