Maven Lifecycle and Dependency Scope

About

Maven organizes the build process into well-defined phases, allowing structured execution of tasks like compilation, testing, packaging, and deployment.

Maven has three primary lifecycles:

  • Clean: Removes previous build artifacts.

  • Default (Build): Compiles, tests, packages, and deploys the project.

  • Site: Generates documentation.

Among these, the default lifecycle consists of the following key phases:

Phase

Description

validate

Ensures the project is correct and necessary information is available.

compile

Compiles source code of the project.

test

Runs unit tests using a testing framework (e.g., JUnit, TestNG).

package

Bundles compiled code into a distributable format (JAR, WAR, etc.).

verify

Runs integration tests to ensure package correctness.

install

Installs the package in the local repository (~/.m2) for use by other projects.

deploy

Uploads the package to a remote repository for sharing with others.

Dependency Scope vs. Lifecycle Phases

Maven dependencies are activated based on their scope at different phases of the build lifecycle.

1. compile Phase

  • Converts .java source files to .class bytecode.

  • Dependencies in compile, provided, and system scope are available.

  • test and runtime dependencies are not available.

Example:

mvn compile

2. test Phase

  • Executes unit tests using JUnit/TestNG.

  • Requires compiled source code from compile phase.

  • Dependencies in compile, provided, runtime, and test scopes are available.

Example:

mvn test

Example pom.xml:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.2</version>
    <scope>test</scope>
</dependency>
  • JUnit is available only during test execution.

  • It won't be included in the final JAR/WAR.

3. package Phase

  • Packages compiled code into a JAR/WAR/ZIP.

  • Dependencies in compile, runtime scope are included in the package.

  • provided and test dependencies are not included.

Example:

mvn package

4. verify Phase

  • Runs integration tests to verify the packaged application.

  • Often used with frameworks like Selenium, Cucumber, or REST Assured.

  • Dependencies in compile, runtime, test scopes are available.

Example:

mvn verify

5. install Phase

  • Deploys the built JAR/WAR into the local Maven repository (~/.m2).

  • Useful for sharing dependencies across local projects.

  • Dependencies in compile, runtime scope are packaged.

Example:

mvn install

6. deploy Phase

  • Uploads the package to a remote repository (like Nexus, Artifactory, or Maven Central).

  • Used in CI/CD pipelines for distributing artifacts.

  • Dependencies in compile, runtime scope are deployed.

Example:

mvn deploy

Last updated

Was this helpful?