Maven Tutorial PDF
Maven Tutorial PDF
This tutorial will teach you how to use Maven in your day-to-day life of any
project development using Java.
Audience
This tutorial has been prepared for the beginners to help them understand the
basic functionality of Maven tool. After completing this tutorial you will find
yourself at a moderate level of expertise in using Apache Maven from where you
can take yourself to next levels.
Prerequisites
We assume you are going to use Maven to handle enterprise level Java projects
development. So it is beneficial to have the knowledge of software development,
Java SE, overview of Java EE development and deployment process.
All the content and graphics published in this e-book are the property of
Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain,
copy, distribute or republish any contents or a part of contents of this e-book in
any manner without written consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as
precisely as possible, however, the contents may contain inaccuracies or errors.
Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy,
timeliness or completeness of our website or its contents including this tutorial.
If you discover any errors on our website or in this tutorial, please notify us at
contact@tutorialspoint.com
i
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
1. OVERVIEW ............................................................................................................................ 1
Objective .................................................................................................................................................. 2
System Requirement................................................................................................................................. 4
3. POM...................................................................................................................................... 9
Super POM.............................................................................................................................................. 10
ii
Profile Activation .................................................................................................................................... 32
6. REPOSITORIES ..................................................................................................................... 40
Local Repository...................................................................................................................................... 40
7. PLUGINS.............................................................................................................................. 44
iii
Created Project ....................................................................................................................................... 67
Created POM.xml.................................................................................................................................... 67
Different Archetypes............................................................................................................................... 70
13. SNAPSHOTS......................................................................................................................... 72
app-ui pom.xml....................................................................................................................................... 73
Dependency Scope.................................................................................................................................. 84
Solution .................................................................................................................................................. 89
POM.xml ................................................................................................................................................. 95
iv
Build Web Application ............................................................................................................................ 96
v
Apache Maven
1. OVERVIEW
What is Maven?
Maven is a project management and comprehension tool that provides
developers a complete build lifecycle framework. Development team can
automate the project's build infrastructure in almost no time as Maven uses a
standard directory layout and a default build lifecycle.
In case of multiple development teams environment, Maven can set-up the way
to work as per standards in a very short time. As most of the project setups are
simple and reusable, Maven makes life of developer easy while creating reports,
checks, build and testing automation setups.
Builds
Documentation
Reporting
Dependencies
SCMs
Releases
Distribution
Mailing list
Maven Evolution
Maven was originally designed to simplify building processes in Jakarta Turbine
project. There were several projects and each project contained slightly different
ANT build files. JARs were checked into CVS.
1
Apache Maven
Apache group then developed Maven which can build multiple projects together,
publish projects information, deploy projects, share JARs across several projects
and help in collaboration of teams.
Objective
The primary goal of Maven is to provide developer with the following:
Maven project structure and contents are declared in an xml file, pom.xml,
referred as Project Object Model (POM), which is the fundamental unit of the
entire Maven system. In later chapters, we will explain POM in detail.
Developers do not have to mention each and every configuration detail. Maven
provides sensible default behavior for projects. When a Maven project is created,
Maven creates default project structure. Developer is only required to place files
accordingly and he/she need not to define any configuration in pom.xml.
As an example, following table shows the default values for project source code
files, resource files and other configurations. Assuming, ${basedir} denotes the
project location:
Item Default
Resources ${basedir}/src/main/resources
Tests ${basedir}/src/test
In order to build the project, Maven provides developers with options to mention
life-cycle goals and project dependencies (that rely on Maven plugin capabilities
2
Apache Maven
and on its default conventions). Much of the project management and build
related tasks are maintained by Maven plugins.
Developers can build any given Maven project without the need to understand
how the individual plugins work. We will discuss Maven Plugins in detail in the
later chapters.
Features of Maven
Simple project setup that follows best practices.
Parallel builds: It analyzes the project dependency graph and enables you
to build schedule modules in parallel. Using this, you can achieve the
performance improvements of 20-50%.
3
Apache Maven
2. ENVIRONMENT SETUP
Maven is a Java based tool, so the very first requirement is to have JDK installed
on your machine.
System Requirement
JDK 1.7 or above.
OS Task Command
OS Output
4
Apache Maven
If you do not have Java installed, install the Java Software Development Kit
(SDK) from
http://www.oracle.com/technetwork/java/javase/downloads/index.html. We are
assuming Java 1.7.0.60 as installed version for this tutorial.
OS Output
OS Output
5
Apache Maven
OS Archive name
Windows apache-maven-3.3.1-bin.zip
Linux apache-maven-3.3.1-bin.tar.gz
Mac apache-maven-3.3.1-bin.tar.gz
Linux /usr/local/apache-maven
Mac /usr/local/apache-maven
OS Output
6
Apache Maven
export M2_HOME=/usr/local/apache-maven/apache-maven-
Mac
3.3.1
export M2=$M2_HOME/bin
export MAVEN_OPTS=-Xms256m -Xmx512m
OS Output
OS Task Command
Finally, verify the output of the above commands, which should be as follows:
OS Output
7
Apache Maven
8
Apache Maven
3. POM
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>
9
Apache Maven
</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.
Node Description
This is project root tag. You need to specify the basic schema
Project root
settings such as apache schema and w3.org specification.
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.
10
Apache Maven
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 the
above mentioned example pom.
Now open the command console, go to the folder containing pom.xml and
execute the following mvn command.
C:\MVN\project>mvn help:effective-pom
.....
[INFO] -----------------------------------------------------------------
-------
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------------
-------
[INFO] Total time: < 1 second
[INFO] Finished at: Thu Jul 05 11:41:51 IST 2012
[INFO] Final Memory: 6M/15M
[INFO] -----------------------------------------------------------------
-------
11
Apache Maven
<!-- ==============================================-->
<!-- -->
<!-- Effective POM for project -->
<!-- 'com.companyname.project-group:project-name:jar:1.0' -->
<!-- -->
<!-- ============================================== -->
<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 h
ttp://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>
<build>
<sourceDirectory>C:\MVN\project\src\main\java</sourceDirectory>
<scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
<testSourceDirectory>C:\MVN\project\src\test\java</testSourceDirectory>
<outputDirectory>C:\MVN\project\target\classes</outputDirectory>
<testOutputDirectory>C:\MVN\project\target\test-
classes</testOutputDirectory>
<resources>
12
Apache Maven
<resource>
<mergeId>resource-0</mergeId>
<directory>C:\MVN\project\src\main\resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<mergeId>resource-1</mergeId>
<directory>C:\MVN\project\src\test\resources</directory>
</testResource>
</testResources>
<directory>C:\MVN\project\target</directory>
<finalName>project-1.0</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-2</version>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
13
Apache Maven
<version>2.0</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.4</version>
</plugin>
<plugin>
<artifactId>maven-ear-plugin</artifactId>
<version>2.3.1</version>
</plugin>
<plugin>
<artifactId>maven-ejb-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.5</version>
</plugin>
<plugin>
<artifactId>maven-plugin-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<artifactId>maven-rar-plugin</artifactId>
<version>2.2</version>
14
Apache Maven
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-8</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.3</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>2.0-beta-7</version>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
<version>2.0.4</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-help-plugin</artifactId>
<version>2.1.1</version>
</plugin>
</plugins>
15
Apache Maven
</build>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Repository Switchboard</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Maven Plugin Repository</name>
<url>http://repo1.maven.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<reporting>
<outputDirectory>C:\MVN\project\target/site</outputDirectory>
</reporting>
</project>
In above pom.xml, you can see the default project source folders structure,
output directory, plug-ins required, repositories, reporting directory, which
Maven will be using while executing the desired goals.
17
Apache Maven
4. BUILD LIFE CYCLE
There are always pre and post phases to register goals, which must run prior
to, or after a particular phase.
18
Apache Maven
clean
default(or build)
site
A goal represents a specific task which contributes to the building and managing
of a project. It may be bound to zero or more build phases. A goal not bound to
any build phase could be executed outside of the build lifecycle by direct
invocation.
The order of execution depends on the order in which the goal(s) and the build
phase(s) are invoked. For example, consider the command below. The clean
and package arguments are build phases while the dependency:copy-
dependencies is a goal.
Here the clean phase will be executed first, followed by the dependency:copy-
dependencies goal, and finally package phase will be executed.
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.
We can customize this behavior by mentioning goals in any of the above phases
of clean life cycle.
19
Apache Maven
<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-clean</id>
<phase>pre-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>pre-clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
20
Apache Maven
</goals>
<configuration>
<tasks>
<echo>clean phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.post-clean</id>
<phase>post-clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>post-clean phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Now open command console, go to the folder containing pom.xml and execute
the following mvn command.
C:\MVN\project>mvn post-clean
Maven will start processing and displaying all the phases of clean life cycle.
21
Apache Maven
You can try tuning mvn clean command, which will display pre-
clean and clean. Nothing will be executed for post-clean phase.
22
Apache Maven
process-sources Process the source code, for example, filter any value.
process-test- Process the test source code, for example, filter any
sources values.
process-test-
Process the generated files from test code file compilation.
classes
23
Apache Maven
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.
<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>
24
Apache Maven
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>id.validate</id>
<phase>validate</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>validate phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.compile</id>
<phase>compile</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>compile phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.test</id>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
25
Apache Maven
<configuration>
<tasks>
<echo>test phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.package</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>package phase</echo>
</tasks>
</configuration>
</execution>
<execution>
<id>id.deploy</id>
<phase>deploy</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>deploy phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
26
Apache Maven
</build>
</project>
Now open command console, go the folder containing pom.xml and execute the
following mvn command.
C:\MVN\project>mvn compile
Maven will start processing and display phases of build life cycle up to the
compile phase.
27
Apache Maven
[INFO] -----------------------------------------------------------------
-
[INFO] Total time: 2 seconds
[INFO] Finished at: Sat Jul 07 20:18:25 IST 2012
[INFO] Final Memory: 7M/64M
[INFO] -----------------------------------------------------------------
-
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
<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>
28
Apache Maven
<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>
29
Apache Maven
<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] ------------------------------------------------------------------
[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] ------------------------------------------------------------------
31
Apache Maven
5. BUILD PROFILES
Profile Activation
A Maven Build Profile can be activated in various ways.
Present/missing files.
32
Apache Maven
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
33
Apache Maven
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>
<profiles>
<profile>
<id>test</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>Using env.test.properties</echo>
<copy file="src/main/resources/env.test.properties"
tofile="${project.build.outputDirectory}
/env.properties"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
34
Apache Maven
</build>
</profile>
</profiles>
</project>
Now open the command console, go to the folder containing pom.xml and
execute the following mvn command. Pass the profile name as argument using -
P option.
Maven will start processing and displaying the result of test build profile.
35
Apache Maven
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Again repeat the above three steps, update id to prod and task section for
env.prod.properties.
Now open the command console, go to the folder containing pom.xml and
execute the following mvn commands. Pass the profile names as argument
using -P option.
36
Apache Maven
Add test profile as an active profile using active Profiles node as shown below in
example.
<settings 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/settings-1.0.0.xsd">
<mirrors>
<mirror>
<id>maven.dev.snaponglobal.com</id>
<name>Internal Artifactory Maven repository</name>
<url>http://repo1.maven.org/maven2/</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
<activeProfiles>
<activeProfile>test</activeProfile>
</activeProfiles>
</settings>
Now open command console, go to the folder containing pom.xml and execute
the following mvn command. Do not pass the profile name using -P option.
Maven will display result of test profile being an active profile.
C:\MVN\project>mvn test
37
Apache Maven
The test profile will trigger when the system property "env" is specified with the
value "test". Create an environment variable "env" and set its value as "test".
<profile>
<id>test</id>
<activation>
<property>
<name>env</name>
<value>test</value>
</property>
</activation>
</profile>
Let's open command console, go to the folder containing pom.xml and execute
the following mvn command.
C:\MVN\project>mvn test
<profile>
<id>test</id>
<activation>
<os>
<name>Windows XP</name>
<family>Windows</family>
<arch>x86</arch>
<version>5.1.2600</version>
</os>
</activation>
38
Apache Maven
</profile>
Now open command console, go to the folder containing pom.xml and execute
the following mvn commands. Do not pass the profile name using -P option.
Maven will display result of test profile being an active profile.
C:\MVN\project>mvn test
<profile>
<id>test</id>
<activation>
<file>
<missing>target/generated-
sources/axistools/wsdl2java/com/companyname/group</missing>
</file>
</activation>
</profile>
Now open the command console, go to the folder containing pom.xml and
execute the following mvn commands. Do not pass the profile name using -P
option. Maven will display result of test profile being an active profile.
C:\MVN\project>mvn test
39
Apache Maven
6. REPOSITORIES
Maven repository are of three types. The following illustration will give an idea
regarding these three types.
local
central
remote
Organization’s Internal
Network
Local
Repositor Internet
y
Remote Central
Local Repositor
Repositor Repository
y
y
Local
Repositor
y
Local Repository
Maven local repository is a folder location on your machine. It gets created when
you run any maven command for the first time.
Maven local repository keeps your project's all dependencies (library jars, plugin
jars etc.). When you run a Maven build, then Maven automatically downloads all
the dependency jars into the local repository. It helps to avoid references to
dependencies stored on remote machine every time a project is build.
40
Apache Maven
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:/MyLocalRepository</localRepository>
</settings>
When you run Maven command, Maven will download dependencies to your
custom path.
Central Repository
Maven central repository is repository provided by Maven community. It contains
a large number of commonly used libraries.
When Maven does not find any dependency in local repository, it starts
searching in central repository using following
URL: http://repo1.maven.org/maven2/
Remote Repository
Sometimes, Maven does not find a mentioned dependency in central repository
as well. It then stops the build process and output error message to console. To
prevent such situation, Maven provides concept of Remote Repository, which
is developer's own custom repository containing required libraries or other
project jars.
For example, using below mentioned POM.xml, Maven will download dependency
(not available in central repository) from Remote Repositories mentioned in the
same pom.xml.
41
Apache Maven
<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>
<dependencies>
<dependency>
<groupId>com.companyname.common-lib</groupId>
<artifactId>common-lib</artifactId>
<version>1.0.0</version>
</dependency>
<dependencies>
<repositories>
<repository>
<id>companyname.lib1</id>
<url>http://download.companyname.org/maven2/lib1</url>
</repository>
<repository>
<id>companyname.lib2</id>
<url>http://download.companyname.org/maven2/lib2</url>
</repository>
</repositories>
</project>
42
Apache Maven
Step 3 - If a remote repository has not been mentioned, Maven simply stops
the processing and throws error (Unable to find dependency).
43
Apache Maven
7. PLUGINS
A plugin generally provides a set of goals, which can be executed using the
following syntax:
mvn [plugin-name]:[goal-name]
mvn compiler:compile
Plugin Types
Maven provided the following two types of Plugins:
Type Description
44
Apache Maven
Plugin Description
Example
We've used maven-antrun-plugin extensively in our examples to print data on
console. Refer Build Profiles chapter. Let us understand it in a better way and
create a 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>
45
Apache Maven
<execution>
<id>id.clean</id>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>clean phase</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Next, open the command console and go to the folder containing pom.xml and
execute the following mvn command.
C:\MVN\project>mvn clean
Maven will start processing and displaying the clean phase of clean life cycle.
[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 define phase from where plugin should starts its processing using its
phase element. We've used clean phase.
Maven will then download the plugin if not available in local repository and
start its processing.
47
Apache Maven
8. CREATING JAVA PROJECT
Let's open the command console, go to the C:\MVN directory and execute the
following mvn command.
mvn archetype:generate
-DgroupId=com.companyname.bank
-DartifactId=consumerBanking
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false
Maven will start processing and will create the complete java application project
structure.
48
Apache Maven
Now go to C:/MVN directory. You'll see a java application project created, named
consumer Banking (as specified in artifactId). Maven uses a standard directory
layout as shown below:
Using the above example, we can understand the following key concepts:
49
Apache Maven
(com/companyName/bank).
If you observe, you will find that Maven also created a sample Java Source file
and Java Test file. Open
C:\MVN\consumerBanking\src\main\java\com\companyname\bank folder, you
will see App.java.
package com.companyname.bank;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
package com.companyname.bank;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
50
Apache Maven
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
Developers are required to place their files as mentioned in table above and
Maven handles all the build related complexities.
51
Apache Maven
In the next chapter, we'll discuss how to build and test the project using
maven Build and Test Project.
52
Apache Maven
9. BUILD AND TEST JAVA PROJECT
<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>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
</project>
Here you can see, Maven already added Junit as test framework. By default,
Maven adds a source file App.java and a test file AppTest.java in its default
directory structure, as discussed in the previous chapter.
53
Apache Maven
54
Apache Maven
Results :
You've built your project and created final jar file, following are the key learning
concepts:
We give maven two goals, first to clean the target directory (clean) and then
package the project build output as jar (package).
Maven compiles the source code file(s) and then tests the source code file(s).
>java com.companyname.bank.App
55
Apache Maven
Hello World!
package com.companyname.bank;
package com.companyname.bank;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
Util.printMessage("Hello World!");
}
}
56
Apache Maven
Hello World!
57
Apache Maven
10. EXTERNAL DEPENDENCIES
As you know, Maven does the dependency management using the concept
of Repositories. But what happens if dependency is not available in any of
remote repositories and central repository? Maven provides answer for such
scenario using concept of External Dependency.
For example, let us do the following changes to the project created in ‘Creating
Java Project’ chapter.
Copy any jar into the lib folder. We've used ldapjdk.jar, which is a helper
library for LDAP operations.
Here you are having your own library, specific to the project, which is an usual
case and it contains jars, which may not be available in any repository for
maven to download from. If your code is using this library with Maven, then
Maven build will fail as it cannot download or refer to this library during
compilation phase.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
58
Apache Maven
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.bank</groupId>
<artifactId>consumerBanking</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>consumerBanking</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ldapjdk</groupId>
<artifactId>ldapjdk</artifactId>
<scope>system</scope>
<version>1.0</version>
<systemPath>${basedir}\src\lib\ldapjdk.jar</systemPath>
</dependency>
</dependencies>
</project>
Hope now you are clear about external dependencies and you will be able to
specify external dependencies in your Maven project.
60
Apache Maven
11. PROJECT DOCUMENTS
This tutorial will teach you how to create documentation of the application in one
go. So let's start, go to C:/MVN directory where you had created your
java consumerBanking application using the examples given in the previous
chapters. Open consumerBanking folder and execute the
following mvn command.
C:\MVN>mvn site
61
Apache Maven
Your project documentation is now ready. Maven has created a site within the
target directory.
62
Apache Maven
Format
Description Reference
Name
A Plain Text
APT document http://maven.apache.org/doxia/format.html
format
A Maven 1.x
http://jakarta.apache.org/site/jakarta-
XDoc documentation
site2.html
format
63
Apache Maven
12. PROJECT TEMPLATES
Maven provides users, a very large list of different types of project templates
(614 in numbers) using the concept of Archetype. Maven helps users to quickly
start a new java project using the following command.
mvn archetype:generate
What is Archetype?
Archetype is a Maven plugin whose task is to create a project structure as per its
template. We are going to use quickstart archetype plugin to create a simple
java application here.
C:\MVN>mvn archetype:generate
Maven will start processing and will ask to choose the required archetype.
64
Apache Maven
Maven will ask for the project detail. Enter project detail as asked. Press Enter if
the default value is provided. You can override them by entering your own value.
65
Apache Maven
Maven will ask for the project detail confirmation. Press enter or press Y.
Now Maven will start creating the project structure and will display the following:
[INFO] -----------------------------------------------------------------
------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-quickstart:1.1
[INFO] --------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.companyname.insurance
[INFO] Parameter: packageName, Value: com.companyname.insurance
[INFO] Parameter: package, Value: com.companyname.insurance
[INFO] Parameter: artifactId, Value: health
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\health
[INFO] -----------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------------
[INFO] Total time: 4 minutes 12 seconds
[INFO] Finished at: Fri Jul 13 11:10:12 IST 2012
[INFO] Final Memory: 20M/90M
[INFO] -----------------------------------------------------------------
66
Apache Maven
Created Project
Now go to C:\ > MVN directory. You'll see a java application project created,
named health, which was given as artifactId at the time of project creation.
Maven will create a standard directory layout for the project as shown below:
Created POM.xml
Maven generates a POM.xml file for the project as listed below:
<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.insurance</groupId>
<artifactId>health</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
67
Apache Maven
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Created App.java
Maven generates sample java source file, App.java for the project as listed
below:
Location: C:\ > MVN > health > src > main > java > com >
companyname > insurance > App.java.
package com.companyname.insurance;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
Created AppTest.java
Maven generates sample java source test file, AppTest.java for the project as
listed below:
68
Apache Maven
Location: C:\ > MVN > health > src > test > java > com > companyname
> insurance > AppTest.java.
package com.companyname.insurance;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
69
Apache Maven
Now you can see the power of Maven. You can create any kind of project using
single command in maven and can kick-start your development.
Different Archetypes
Archetype ArtifactIds Description
70
Apache Maven
71
Apache Maven
13. SNAPSHOTS
Now it may happen that team working on data-service is undergoing bug fixing
or enhancements at rapid pace and they are releasing the library to remote
repository almost every other day.
Now if data-service team uploads a new version every other day, then following
problems will arise:
data-service team should tell app-ui team every time when they have
released an updated code.
app-ui team required to update their pom.xml regularly to get the updated
version.
What is SNAPSHOT?
SNAPSHOT is a special version that indicates a current development copy. Unlike
regular versions, Maven checks for a new SNAPSHOT version in a remote
repository for every build.
Now data-service team will release SNAPSHOT of its updated code every time to
repository, say data-service: 1.0-SNAPSHOT, replacing an older SNAPSHOT jar.
Snapshot vs Version
In case of Version, if Maven once downloaded the mentioned version, say data-
service:1.0, it will never try to download a newer 1.0 available in repository. To
download the updated code, data-service version is be upgraded to 1.1.
72
Apache Maven
app-ui pom.xml
app-ui project is using 1.0-SNAPSHOT of data-service.
<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>app-ui</groupId>
<artifactId>app-ui</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>data-service</groupId>
<artifactId>data-service</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
data-service pom.xml
data-service project is releasing 1.0-SNAPSHOT for every minor change.
<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">
73
Apache Maven
<modelVersion>4.0.0</modelVersion>
<groupId>data-service</groupId>
<artifactId>data-service</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>health</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Let's open the command console, go to the C:\ > MVN > app-ui directory and
execute the following mvn command.
Maven will start building the project after downloading the latest SNAPSHOT of
data-service.
Results :
75
Apache Maven
76
Apache Maven
14. BUILD AUTOMATION
Build Automation defines the scenario where dependent project(s) build process
gets started once the project build is successfully completed, in order to ensure
that dependent project(s) is/are stable.
Example
Consider a team is developing a project bus-core-api on which two other
projects app-web-ui and app-desktop-ui are dependent.
<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>app-web-ui</groupId>
<artifactId>app-web-ui</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
<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">
77
Apache Maven
<modelVersion>4.0.0</modelVersion>
<groupId>app-desktop-ui</groupId>
<artifactId>app-desktop-ui</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
bus-core-api project:
<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>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
</project>
Using snapshot, ensures that the latest bus-core-api project should be used
but to meet the above requirement we need to do something extra.
Using Maven
Update bus-core-api project pom.xml.
<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>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>1.6</version>
<configuration>
<debug>true</debug>
<pomIncludes>
<pomInclude>app-web-ui/pom.xml</pomInclude>
<pomInclude>app-desktop-ui/pom.xml</pomInclude>
</pomIncludes>
</configuration>
<executions>
<execution>
<id>build</id>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
79
Apache Maven
<build>
</project>
Let's open the command console, go to the C:\ > MVN > bus-core-
api directory and execute the following mvn command.
Once bus-core-api build is successful, Maven will start building the app-web-
ui project.
[INFO] -----------------------------------------------------------------
-
[INFO] Building app-web-ui
[INFO] task-segment: [package]
[INFO] -----------------------------------------------------------------
-
...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-web-ui\target\
80
Apache Maven
app-web-ui-1.0-SNAPSHOT.jar
[INFO] -----------------------------------------------------------------
-
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------------
-
Once app-web-ui build is successful, Maven will start building the app-
desktop-ui project.
[INFO] -----------------------------------------------------------------
-
[INFO] Building app-desktop-ui
[INFO] task-segment: [package]
[INFO] -----------------------------------------------------------------
-
...
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: C:\MVN\app-desktop-ui\target\
app-desktop-ui-1.0-SNAPSHOT.jar
[INFO] -----------------------------------------------------------------
--
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------------
--
81
Apache Maven
Hudson considers each project build as job. Once a project code is checked-in to
SVN (or any Source Management Tool mapped to Hudson), Hudson starts its
build job and once this job gets completed, it start other dependent jobs (other
dependent projects) automatically.
82
Apache Maven
15. DEPENDENCY MANAGEMENT
Maven helps to avoid such requirements to discover all the libraries required.
Maven does so by reading project files (pom.xml) of dependencies, figure out
their dependencies and so on.
We only need to define direct dependency in each project pom. Maven handles
the rest automatically.
With transitive dependencies, the graph of included libraries can quickly grow to
a large extent. Cases can arise when there are duplicate libraries. Maven
provides few features to control extent of transitive dependencies.
Feature Description
Dependency Scope
Transitive Dependencies Discovery can be restricted using various Dependency
Scope as mentioned below.
Scope Description
This scope indicates that the dependency is only available for the
test
test compilation and execution phases.
system This scope indicates that you have to provide the system path.
Dependency Management
Usually, we have a set of project under a common project. In such case, we can
create a common pom having all the common dependencies and then make this
pom, the parent of sub-project's poms. Following example will help you
understand this concept.
84
Apache Maven
Lib1:1
.0
Lib3:3.
App-Data-
1.1
lib:1.0
App-UI-WAR
<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.groupname</groupId>
<artifactId>App-UI-WAR</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.companyname.groupname</groupId>
<artifactId>App-Core-lib</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<dependencies>
85
Apache Maven
<dependency>
<groupId>com.companyname.groupname</groupId>
<artifactId>App-Data-lib</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
</project>
App-Core-lib
<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">
<parent>
<artifactId>Root</artifactId>
<groupId>com.companyname.groupname</groupId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.groupname</groupId>
<artifactId>App-Core-lib</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
</project>
App-Data-lib
<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">
<parent>
<artifactId>Root</artifactId>
<groupId>com.companyname.groupname</groupId>
86
Apache Maven
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.groupname</groupId>
<artifactId>App-Data-lib</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
</project>
Root
<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.groupname</groupId>
<artifactId>Root</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<dependencies>
<dependency>
<groupId>com.companyname.groupname1</groupId>
<artifactId>Lib1</artifactId>
<version>1.0</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>com.companyname.groupname2</groupId>
<artifactId>Lib2</artifactId>
<version>2.1</version>
</dependency>
</dependencies>
87
Apache Maven
<dependencies>
<dependency>
<groupId>com.companyname.groupname3</groupId>
<artifactId>Lib3</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
Now when we build App-UI-WAR project, Maven will discover all the
dependencies by traversing the dependency graph and build the application.
88
Apache Maven
16. DEPLOYMENT AUTOMATION
Check-in the code from all project in progress into the SVN (version control
system) or source code repository and tag it.
Store the build output either WAR or EAR file to a common network location.
Get the file from network and deploy the file to the production site.
Updated the documentation with date and updated version number of the
application.
Problem Statement
There are normally multiple people involved in the above mentioned deployment
process. One team may handle check-in of code, other may handle build and so
on. It is very likely that any step may be missed out due to manual efforts
involved and owing to multi-team environment. For example, older build may
not be replaced on network machine and deployment team deployed the older
build again.
Solution
Automate the deployment process by combining the following:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
89
Apache Maven
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>bus-core-api</groupId>
<artifactId>bus-core-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<scm>
<url>http://www.svn.com</url>
<connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/
Framework</connection>
<developerConnection>scm:svn:${username}/${password}@localhost:8080:
common_core_api:1101:code</developerConnection>
</scm>
<distributionManagement>
<repository>
<id>Core-API-Java-Release</id>
<name>Release repository</name>
<url>http://localhost:8081/nexus/content/repositories/
Core-Api-Release</url>
</repository>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-9</version>
<configuration>
<useReleaseProfile>false</useReleaseProfile>
<goals>deploy</goals>
<scmCommentPrefix>[bus-core-api-release-checkin]-<
/scmCommentPrefix>
90
Apache Maven
</configuration>
</plugin>
</plugins>
</build>
</project>
Element Description
Configures the SVN location from where Maven will check out the
SCM
source code.
mvn release:clean
It cleans the workspace in case the last release process was not successful.
mvn release:rollback
Rollback the changes done to workspace code and configuration in case the last
release process was not successful.
mvn release:prepare
Changes the version of the application and removes SNAPSHOT from the
version to make release.
Increment the version number and append SNAPSHOT for future release.
mvn release:perform
Checks out the code using the previously defined tag and run the Maven deploy
goal, to deploy the war or built artifact to repository.
Let's open the command console, go to the C:\ > MVN >bus-core-
api directory and execute the following mvn command.
>mvn release:prepare
Maven will start building the project. Once build is successful run the
following mvn command.
>mvn release:perform
Once build is successful you can verify the uploaded JAR file in your repository.
92
Apache Maven
17. WEB APPLICATION
This chapter teaches you how to manage a web based project using Maven.
Here you will learn how to create/build/deploy and run a web application.
C:\MVN>mvn archetype:generate
-DgroupId=com.companyname.automobile
-DartifactId=trucks
-DarchetypeArtifactId=maven-archetype-webapp
-DinteractiveMode=false
Maven will start processing and will create the complete web based java
application project structure as follows:
93
Apache Maven
Now go to C:/MVN directory. You'll see a java application project created, named
trucks (as specified in artifactId) as specified in the following snapshot. The
following directory structure is generally used for web applications:
Maven uses a standard directory layout. Using the above example, we can
understand the following key concepts:
94
Apache Maven
POM.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.automobile</groupId>
<artifactId>trucks</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>trucks Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>trucks</finalName>
</build>
</project>
If you observe, you will find that Maven also created a sample JSP Source file.
95
Apache Maven
Open C:\ > MVN > trucks > src > main > webapp > folder to see index.jsp
with the following code:
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
97
Apache Maven
98
Apache Maven
18. ECLIPSE IDE INTEGRATION
You can view the output of Maven commands inside the Eclipse, using its own
console.
It does the dependency management for Eclipse build path based on Maven's
pom.xml.
It provides wizards for creating new Maven projects, pom.xml and to enable
Maven support on existing projects
Eclipse URL
Following example will help you to leverage benefits of integrating Eclipse and
maven.
99
Apache Maven
Select Project location, where a project was created using Maven. We've
created a Java Project consumer Banking in the previous chapters. Go
to ‘Creating Java Project’ chapter, to see how to create a project using
Maven.
100
Apache Maven
Now, have a look at consumer Banking project properties. You can see that
Eclipse has added Maven dependencies to java build path.
101
Apache Maven
Maven will start building the project. You can see the output in Eclipse Console
as follows:
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire: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.047
sec
Results :
[INFO] [jar:jar]
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Thu Jul 12 18:18:24 IST 2012
[INFO] Final Memory: 2M/15M
[INFO] -------------------------------------------------------------------
Now, right click on App.java. Select Run As option. Then select Java
Application.
103
Apache Maven
Hello World!
104
Apache Maven
19. NETBEANS IDE INTEGRATION
NetBeans 6.7 and newer has in-built support for Maven. In case of previous
version, Maven plugin is available in plugin Manager. We are using NetBeans 6.9
in this example.
You can view the output of Maven commands inside the NetBeans using its
own console.
NetBeans provides a Maven Repository browser that enables you to view your
local repository and registered external Maven repositories.
Following example will help you to leverage benefits of integrating NetBeans and
Maven.
Select Project location, where a project was created using Maven. We've
created a Java Project consumerBanking. Go to ‘Creating Java Project’
chapter, to see how to create a project using Maven.
105
Apache Maven
Now, you can see the maven project in NetBeans. Have a look at
consumerBanking project Libraries and Test Libraries. You can see that
NetBeans has added Maven dependencies to its build path.
106
Apache Maven
Maven will start building the project. You can see the output in NetBeans
Console as follows:
107
Apache Maven
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.companyname.bank.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023
sec
Results :
108
Apache Maven
[jar:jar]
Building jar: C:\MVN\consumerBanking\target\consumerBanking-1.0-
SNAPSHOT.jar
[install:install]
Installing C:\MVN\consumerBanking\target\consumerBanking-1.0-
SNAPSHOT.jar
to C:\Users\GB3824\.m2\repository\com\companyname\bank\consumerBanking\
1.0-SNAPSHOT\consumerBanking-1.0-SNAPSHOT.jar
------------------------------------------------------------------------
BUILD SUCCESSFUL
------------------------------------------------------------------------
Total time: 9 seconds
Finished at: Thu Jul 19 12:57:28 IST 2012
Final Memory: 16M/85M
------------------------------------------------------------------------
110
Apache Maven
20. INTELLIJ IDEA IDE INTEGRATION
IntelliJ IDEA has in-built support for Maven. We are using IntelliJ IDEA
Community Edition 11.1 in this example.
You can view the output of Maven commands inside the IntelliJ IDEA using its
own console.
IntelliJ IDEA provides wizards for creating new Maven projects, pom.xml.
Following example will help you to leverage benefits of integrating IntelliJ IDEA
and Maven.
111
Apache Maven
Select Project location, where a project was created using Maven. We have
created a Java Project consumerBanking. Go to ‘Creating Java
Project' chapter, to see how to create a project using Maven.
112
Apache Maven
113
Apache Maven
Now, you can see the maven project in IntelliJ IDEA. Have a look at
consumerBanking project external libraries. You can see that IntelliJ IDEA
has added Maven dependencies to its build path under Maven section.
114
Apache Maven
115
Apache Maven
"C:\Program Files\Java\jdk1.6.0_21\bin\java"
-Didea.launcher.port=7533
"-Didea.launcher.bin.path=
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 11.1.2\bin"
-Dfile.encoding=UTF-8
-classpath "C:\Program Files\Java\jdk1.6.0_21\jre\lib\charsets.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\rt.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.6.0_21\jre\lib\ext\sunpkcs11.jar
C:\MVN\consumerBanking\target\classes;
C:\Program Files\JetBrains\
IntelliJ IDEA Community Edition 11.1.2\lib\idea_rt.jar"
com.intellij.rt.execution.application.AppMain com.companyname.bank.App
Hello World!
116