Maven Life Cycle and Commands

POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides in the base directory of the project as pom.xml.
The POM contains information about the project and various configuration detail used by Maven to build the project(s).
POM also contains the goals and plugins. While executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, and then executes the goal. Some of the configuration that can be specified in the POM are following −
  • project dependencies
  • plugins
  • goals
  • build profiles
  • project version
  • developers
  • mailing list
Before creating a POM, we should first decide the project group (groupId), its name (artifactId) and its version as these attributes help in uniquely identifying the project in repository.

POM Example

<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>com.companyname.project-group</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
</project>
It should be noted that there should be a single POM file for each project.
  • All POM files require the project element and three mandatory fields: groupId, artifactId, version.
  • Projects notation in repository is groupId:artifactId:version.
  • Minimal requirements for a POM −
Sr.No. Node & Description
1 Project root
This is project root tag. You need to specify the basic schema settings such as apache schema and w3.org specification.
2 Model version
Model version should be 4.0.0.
3 groupId
This is an Id of project's group. This is generally unique amongst an organization or a project. For example, a banking group com.company.bank has all bank related projects.
4 artifactId
This is an Id of the project. This is generally name of the project. For example, consumer-banking. Along with the groupId, the artifactId defines the artifact's location within the repository.
5 version
This is the version of the project. Along with the groupId, It is used within an artifact's repository to separate versions from each other. For example −
com.company.bank:consumer-banking:1.0
com.company.bank:consumer-banking:1.1.

Super POM

The Super POM is Maven’s default POM. All POMs inherit from a parent or default (despite explicitly defined or not). This base POM is known as the Super POM, and contains values inherited by default.
Maven use the effective POM (configuration from super pom plus project configuration) to execute relevant goal. It helps developers to specify minimum configuration detail in his/her pom.xml. Although configurations can be overridden easily.
An easy way to look at the default configurations of the super POM is by running the following command: mvn help:effective-pom
Create a pom.xml in any directory on your computer.Use the content of above mentioned example pom.
In example below, We've created a pom.xml in C:\MVN\project folder.
Now open command console, go the folder containing pom.xml and execute the following mvn command.
C:\MVN\project>mvn help:effective-pom

What is Build Lifecycle?

A Build Lifecycle is a well-defined sequence of phases, which define the order in which the goals are to be executed. Here phase represents a stage in life cycle.

When Maven starts building a project, it steps through a defined sequence of phases and executes goals, which are registered with each phase.
Maven has the following three standard lifecycles −
  • clean
  • default(or build)
  • site

Clean Lifecycle

When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the following phases.
  • pre-clean
  • clean
  • post-clean
Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:cleangoal deletes the output of a build by deleting the build directory. Thus, when mvn clean command executes, Maven deletes the build directory.


Default (or Build) Lifecycle

This is the primary life cycle of Maven and is used to build the application. It has the following 23 phases.
Sr.No.Lifecycle Phase & Description
1
validate
Validates whether project is correct and all necessary information is available to complete the build process.
2
initialize
Initializes build state, for example set properties.
3
generate-sources
Generate any source code to be included in compilation phase.
4
process-sources
Process the source code, for example, filter any value.
5
generate-resources
Generate resources to be included in the package.
6
process-resources
Copy and process the resources into the destination directory, ready for packaging phase.
7
compile
Compile the source code of the project.
8
process-classes
Post-process the generated files from compilation, for example to do bytecode enhancement/optimization on Java classes.
9
generate-test-sources
Generate any test source code to be included in compilation phase.
10
process-test-sources
Process the test source code, for example, filter any values.
11
test-compile
Compile the test source code into the test destination directory.
12
process-test-classes
Process the generated files from test code file compilation.
13
test
Run tests using a suitable unit testing framework (Junit is one).
14
prepare-package
Perform any operations necessary to prepare a package before the actual packaging.
15
package
Take the compiled code and package it in its distributable format, such as a JAR, WAR, or EAR file.
16
pre-integration-test
Perform actions required before integration tests are executed. For example, setting up the required environment.
17
integration-test
Process and deploy the package if necessary into an environment where integration tests can be run.
18
post-integration-test
Perform actions required after integration tests have been executed. For example, cleaning up the environment.
19
verify
Run any check-ups to verify the package is valid and meets quality criteria.
20
install
On a mvn install, it frames a dependency tree based on the project configuration pom.xml on all the sub projects under the super pom.xml (the root POM) and downloads/compiles all the needed components in a directory called .m2 under the user's folder. These dependencies will have to be resolved for the project to be built without any errors, and mvn install is one utility that could download most of the dependencies.
21
deploy
Copies the final package to the remote repository for sharing with other developers and projects.
There are few important concepts related to Maven Lifecycles, which are worth to mention −
  • When a phase is called via Maven command, for example mvn compile, only phases up to and including that phase will execute.
  • Different maven goals will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR / WAR / EAR).
C:\MVN\project>mvn post-clean
Maven will start processing and displaying all the phases of clean life cycle.
[INFO] Scanning for projects...
[INFO] -----------------------------------------------------------------
-
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [post-clean]
[INFO] ------------------------------------------------------------------
[INFO] [antrun:run {execution: id.pre-clean}]
[INFO] Executing tasks
[echo] pre-clean phase
[INFO] Executed tasks
[INFO] [clean:clean {execution: default-clean}]
[INFO] [antrun:run {execution: id.clean}]
[INFO] Executing tasks
[echo] clean phase
[INFO] Executed tasks
[INFO] [antrun:run {execution: id.post-clean}]
[INFO] Executing tasks
[echo] post-clean phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: > 1 second
[INFO] Finished at: Sat Jul 07 13:38:59 IST 2012
[INFO] Final Memory: 4M/44M
[INFO] ------------------------------------------------------------------
You can try tuning mvn clean command, which will display pre-clean and clean. Nothing will be executed for post-clean phase.

C:\MVN\project>mvn compile
Maven will start processing and display phases of build life cycle up to the compile phase.
[INFO] Scanning for projects...
[INFO] -----------------------------------------------------------------
-
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [compile]
[INFO] -----------------------------------------------------------------
-
[INFO] [antrun:run {execution: id.validate}]
[INFO] Executing tasks
[echo] validate phase
[INFO] Executed tasks
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered
resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory
C:\MVN\project\src\main\resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [antrun:run {execution: id.compile}]
[INFO] Executing tasks
[echo] compile phase
[INFO] Executed tasks
[INFO] -----------------------------------------------------------------
-
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------------
-
[INFO] Total time: 2 seconds
[INFO] Finished at: Sat Jul 07 20:18:25 IST 2012
[INFO] Final Memory: 7M/64M
[INFO] -----------------------------------------------------------------

C:\MVN\consumerBanking>mvn clean package
Maven will start building the project.
[INFO] Scanning for projects...
[INFO] -------------------------------------------------------------------
[INFO] Building consumerBanking
[INFO] task-segment: [clean, package]
[INFO] -------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory C:\MVN\consumerBanking\target
[INFO] [resources:resources {execution: default-resources}]

[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\main\resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\classes
[INFO] [resources:testResources {execution: default-testResources}]

[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory C:\MVN\consumerBanking\src\test\resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to C:\MVN\consumerBanking\target\test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: C:\MVN\consumerBanking\target\surefire-reports

-----------------------------------------------------
T E S T S
-----------------------------------------------------

Running com.companyname.bank.AppTest

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.027 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\consumerBanking\target\
consumerBanking-1.0-SNAPSHOT.jar

[INFO]-----------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO]-----------------------------------------------

[INFO] Total time: 2 seconds
[INFO] Finished at: Tue Jul 10 16:52:18 IST 2012
[INFO] Final Memory: 16M/89M
[INFO]---------------------------------------------

Build Web Application

Let's open the command console, go to the C:\MVN\trucks directory and execute the following mvn command.
C:\MVN\trucks>mvn clean package
Maven will start building the project.
[INFO] Scanning for projects...
[INFO] -------------------------------------------------------------------
[INFO] Building trucks Maven Webapp
[INFO] task-segment: [clean, package]
[INFO] -------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] [resources:resources {execution: default-resources}]

[WARNING] Using platform encoding (Cp1252 actually) to
copy filtered resources,i.e. build is platform dependent!

[INFO] Copying 0 resource
[INFO] [compiler:compile {execution: default-compile}]
[INFO] No sources to compile
[INFO] [resources:testResources {execution: default-testResources}]

[WARNING] Using platform encoding (Cp1252 actually) to
copy filtered resources,i.e. build is platform dependent!

[INFO] skip non existing resourceDirectory
C:\MVN\trucks\src\test\resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] No sources to compile
[INFO] [surefire:test {execution: default-test}]
[INFO] No tests to run.
[INFO] [war:war {execution: default-war}]
[INFO] Packaging webapp
[INFO] Assembling webapp[trucks] in [C:\MVN\trucks\target\trucks]
[INFO] Processing war project
[INFO] Copying webapp resources[C:\MVN\trucks\src\main\webapp]
[INFO] Webapp assembled in[77 msecs]
[INFO] Building war: C:\MVN\trucks\target\trucks.war
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Tue Jul 17 11:22:45 IST 2012
[INFO] Final Memory: 11M/85M
[INFO] ------------

Summary Commands
Project Build
Clean a project: mvn clean
Compile a project: mvn compile
Run unit tests (it also compiles a project): mvn test
Build a package (it also executes unit tests): mvn package
Run integration test (it also builds a package): mvn verify
Install a package into local repository (it also executes integration tests): mvn install
Install an artifact into local repository (skip integration test execution): mvn -DskipITs=true install
Install an artifact into local repository (skip unit and integration test execution): mvn -DskipTests=true install
Install an artifact into local repository (skip compiling test and test execution): mvn -Dmaven.test.skip=true
Deploy artifact into enterprise repository: mvn deploy
Run Spring Boot application
$ mvn spring-boot:run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.0.4.RELEASE)
....... . . .
....... . . . (log output here)
....... . . .
........ Started Example in 2.222 seconds (JVM running for 6.514)

Site Lifecycle

Maven Site plugin is generally used to create fresh documentation to create reports, deploy site, etc. It has the following phases −
  • pre-site
  • site
  • post-site
  • site-deploy
In the following example, we will attach maven-antrun-plugin:run goal to all the phases of Site lifecycle. This will allow us to echo text messages displaying the phases of the lifecycle.
We've updated pom.xml in C:\MVN\project folder.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.companyname.projectgroup</groupId>
   <artifactId>project</artifactId>
   <version>1.0</version>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
               <execution>
                  <id>id.pre-site</id>
                  <phase>pre-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>pre-site phase</echo>
                     </tasks>
                  </configuration>
               </execution>
               
               <execution>
                  <id>id.site</id>
                  <phase>site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>site phase</echo>
                     </tasks>
                  </configuration>
               </execution>
               
               <execution>
                  <id>id.post-site</id>
                  <phase>post-site</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>post-site phase</echo>
                     </tasks>
                  </configuration>
               </execution>
               
               <execution>
                  <id>id.site-deploy</id>
                  <phase>site-deploy</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
                  <configuration>
                     <tasks>
                        <echo>site-deploy phase</echo>
                     </tasks>
                  </configuration>
               </execution>
               
            </executions>
         </plugin>
      </plugins>
   </build>
</project>
Now open the command console, go the folder containing pom.xml and execute the following mvn command.
C:\MVN\project>mvn site
Maven will start processing and displaying the phases of site life cycle up to site phase.

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------
[INFO] Building Unnamed - com.companyname.projectgroup:project:jar:1.0
[INFO] task-segment: [site]
[INFO] ------------------------------------------------------------------
[INFO] [antrun:run {execution: id.pre-site}]
[INFO] Executing tasks
[echo] pre-site phase
[INFO] Executed tasks
[INFO] [site:site {execution: default-site}]

[INFO] Generating "About" report.
[INFO] Generating "Issue Tracking" report.
[INFO] Generating "Project Team" report.
[INFO] Generating "Dependencies" report.
[INFO] Generating "Project Plugins" report.
[INFO] Generating "Continuous Integration" report.
[INFO] Generating "Source Repository" report.
[INFO] Generating "Project License" report.
[INFO] Generating "Mailing Lists" report.
[INFO] Generating "Plugin Management" report.
[INFO] Generating "Project Summary" report.

[INFO] [antrun:run {execution: id.site}]
[INFO] Executing tasks
[echo] site phase
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Sat Jul 07 15:25:10 IST 2012
[INFO] Final Memory: 24M/149M
[INFO] ------------------------------------------------------------------

Comments

Popular posts from this blog

gsutil Vs Storage Transfer Service Vs Transfer Appliance

SQL basic interview question