Sub topic 6
Maven Lifecycles, Phases, and Goals
In the last chapter you wrote a pom.xml. Now you will use it to build. Maven does not ask you to list every build step yourself. It follows a fixed plan called a lifecycle.
Three Words to Know
- A lifecycle is a named, ordered list of build steps. Maven has three:
default(builds your project),clean(deletes old output), andsite(makes documentation). - A phase is one step in a lifecycle, such as
compileortest. - A goal is one specific job done by a plugin. A plugin is a piece of code that adds a feature to Maven. For example,
compiler:compileis thecompilegoal of the compiler plugin.
Phases name the steps, and goals do the actual work. Maven attaches goals to phases for you, based on the packaging value in your POM.
The Default Lifecycle
These are the main phases of the default lifecycle, in order:
| Phase | What happens | Goal Maven attaches for a jar project |
|---|---|---|
| `validate` | Checks that the POM is correct | none |
| `compile` | Compiles `src/main/java` | `compiler:compile` |
| `test` | Compiles and runs tests | `compiler:testCompile`, `surefire:test` |
| `package` | Builds the JAR file | `jar:jar` |
| `verify` | Runs extra checks | none |
| `install` | Copies the JAR to your local cache | `install:install` |
| `deploy` | Uploads the JAR to a shared repository | `deploy:deploy` |
The Key Rule: Earlier Phases Run First
When you ask for a phase, Maven runs every phase before it as well. So mvn package validates, compiles, tests, and then packages. You never have to type the earlier steps.
Try it in the project from the previous chapter:
mvn compile
mvn test
mvn package
java -cp target/hello-1.0-SNAPSHOT.jar com.example.App
mvn dependency:tree
mvn clean verifyHere is what each line does:
mvn compileputs.classfiles intarget/classes.mvn testcompiles again if needed, then runs the tests.mvn packagecreatestarget/hello-1.0-SNAPSHOT.jar.- The
javacommand runs the app from that JAR and printsHello, World!. mvn dependency:treeruns a single goal directly. It runs no phases. It prints your dependencies.mvn clean verifyruns two lifecycles in a row. Firstcleandeletestarget/, then the default lifecycle runs up toverify.
Phase or Goal?
The command tells you which kind you typed. A name with a colon, like dependency:tree, is a goal. A plain name, like package, is a phase.
Exercise
You run mvn install. Which phases of the default lifecycle run, and in what order?
Show answer
validate, compile, test, package, verify, and then install. Asking for a phase always runs every earlier phase first.
Exercise
Is surefire:test a phase or a goal? How can you tell?
Show answer
It is a goal. The colon shows it is the test goal of the Surefire plugin. Maven runs this goal during the test phase.