Java · Intermediate level

Intermediate level · Module 4: Packages and Builds with Maven · Lesson 3 of 3

The Maven Build Lifecycle

Run Maven's lifecycle phases from the command line and package the application as a runnable JAR.

In this lesson you will

  • Run mvn compile, test, package and clean and explain what each does
  • Configure and run an executable JAR

Key concepts

lifecycle phasemvn packagetarget folderMain-Class manifest

The lesson

Maven builds in ordered phases. Running a phase runs every phase before it: mvn package validates, compiles, runs the tests and then creates a JAR in the target folder. If any test fails, packaging stops, which protects you from shipping broken code.

mvn clean deletes the target folder so the next build starts fresh. When a build behaves strangely, mvn clean package is a good first step.

To run a JAR with java -jar app.jar, its manifest must name the main class. In Maven this is set with a plugin configuration in pom.xml. Running the packaged JAR from the terminal proves the application works outside the IDE.

Step by step

  1. Run mvn compile and inspect target/classes.
  2. Run mvn test and read the test report.
  3. Configure the main class and run mvn package.
  4. Run the application with java -jar.
Workflow

What happens when you run mvn package

The Maven build phases that run, in order, every time you package an application.

  1. validate

    Checks the project and pom.xml are correct.

    Maven

  2. compile

    Compiles src/main/java into target/classes.

    compiler plugin

  3. test

    Compiles and runs the tests in src/test/java; a failing test stops the build.

    surefire plugin

  4. package

    Bundles the compiled classes into a JAR in the target folder.

    jar plugin

  5. run

    java -jar target/app.jar starts the application outside the IDE.

    you

Change code, run mvn package, fix whatever fails, repeat. Use mvn clean package when the build behaves strangely.

Why it works

Running a phase runs every phase before it, so you cannot package an application whose tests fail — a useful safety net.

Practice activity

Package the library application as an executable JAR and run it on a classmate's computer.

Expected result: The JAR runs with java -jar on another machine that has a JDK installed.

Check your understanding

  1. What does mvn package do before creating the JAR?

    Show answer

    It runs the earlier phases, including compiling and running the tests.

  2. What does mvn clean remove?

    Show answer

    The target folder with all build output.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.