You are on page 1of 16

Dr. D. Y.

Patil Pratishthan’s
D. Y. Patil Institute of Master of Computer Applications and Management
(Approved by AICTE, New Delhi & Affiliated to Savitribai Phule Pune University)
Dr. D. Y. Patil Educational Complex, Sector 29, Pradhikaran, Akurdi, Pune – 411 044
Tel No: (020)27640998, Website: www.dypimca.ac.in, E-mail : director@dypimca.ac.in
----------------------------------------------------------------------------------------------------------------------

MONOGRAPH

Subject Code: IT-41 DevOps


Unit 5. Build Tool - Maven
Maven
• Maven is a powerful build automation tool that is primarily used for Java-based projects.
• Maven helps you tackle two critical aspects of building software –
• It describes how software is built
• It describes the dependencies

Convention over Configuration

• Maven uses Convention over Configuration, which means developers are not required to create
build process themselves.
• 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

source code ${basedir}/src/main/java

Resources ${basedir}/src/main/resources

Tests ${basedir}/src/test

Complied byte code ${basedir}/target

distributable JAR ${basedir}/target/classes

When should someone use Maven?

• If there are too many dependencies for the project.

• When the dependency version update frequently.


• Continuous builds, integration, and testing can be easily handled by using maven.
• When one needs an easy way to generate documentation from the source code, compiling the
source code, packaging compiled code into JAR files or ZIP files.
5.1. Maven Installation
Step 1 - Verify Java Installation in Your Machine
c:\> java –version
Step 2 - Set JAVA Environment
Set the environment variable JAVA_HOME to C:\Program Files\Java\jdk11.0.11
Step 3 - Download Maven Archive
Download Maven 3.8.4 from https://maven.apache.org/download.cgi.
Step 4 - Extract the Maven Archive
Extract the archive, to the directory you wish to install Maven 3.8.4. The subdirectory apache-maven-
3.8.4 will be created from the archive.
C:\Program Files\Apache Software Foundation\apache-maven-3.8.4
Step 5 - Set Maven Environment Variables
Add M2_HOME, M2, MAVEN_OPTS to environment variables.
Set the environment variables using system properties.
M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.8.4
M2=%M2_HOME%\bin
MAVEN_OPTS=-Xms256m -Xmx512m
Step 6 - Add Maven bin Directory Location to System Path
Append M2 variable to System Path.
Append the string ; %M2% to the end of the system variable, Path.
Step 7 - Verify Maven Installation
Now open console and execute the following mvn command.
c:\> mvn –version

5.2. Maven Build requirements


1. Configure Maven in Java, using Project Object Model (POM) found in a pom.xml file.

2. All Maven-related configuration settings are found in the POM. You can edit and configure plug-
ins in the <plugins> tag of a pom.xml file.

3. Maven provides default settings for configurations, so you don’t have to add every configuration
into the pom.xml file.
5.3. Maven POM Builds (pom.xml)
• The pom.xml file contains information about the project and configuration information to build
the project.
• It contains dependencies, build directory, source directory, test source directory, plugin, etc.
Maven goes through the pom.xml file, then executes the goal.
• Contents of pom.xml file:
• project : Root element of a pom.xml file.
• groupId: Sub element of the project. It describes the Id for the project.
• modelVersion: Sub element of the project. It tells you the model version.
• artifactId: Sub element of the project. It specifies the id for the project. An artifact is
either produced or used by a project. Examples of artifacts: JARs, source and binary
distributions, and WARs.
• Version: Sub element of the project. It tells you the version of the artifact under given
group.
There are some additional elements in pom.xml file:
• Packaging: defines the packaging type such as war, jar etc.
• Scope: defines the scope for the maven project.
• Url: specifies the URL of the project.
• Name: defines the name of the maven project.
• Dependency: defines a dependency. It is used inside dependencies.
Sample a pom.xml file
<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"&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.edureka.application1</groupId>
<artifactId>my-application1</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Maven Quick Start Archetype</name>
<ur>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

5.4. Maven Build Life Cycle


Maven Architecture

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.
A typical Maven Build Lifecycle consists of the following sequence of phases.

Phase Handles Description

prepare- resource copying Resource copying can be customized in this phase.


resources

validate Validating the Validates if the project is correct and if all necessary
information information is available.

compile compilation Source code compilation is done in this phase.

Test Testing Tests the compiled source code suitable for testing framework.

package packaging This phase creates the JAR/WAR package as mentioned in the
packaging in POM.xml.

install installation This phase installs the package in local/remote maven


repository.

Deploy Deploying Copies the final package to the remote repository.


Maven has the following three standard lifecycles −

 clean
 default(or build)
 site

1. 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.

2. Default (or Build) Lifecycle


This is the primary life cycle of Maven and is used to build the application. It has the following 21
phases.

Lifecycle Phase Description

validate Validates whether project is correct and all necessary information is


available to complete the build process.

initialize Initializes build state, for example set properties.

generate-sources Generate any source code to be included in compilation phase.

process-sources Process the source code, for example, filter any value.

generate-resources Generate resources to be included in the package.

process-resources Copy and process the resources into the destination directory, ready for
packaging phase.

compile Compile the source code of the project.

process-classes Post-process the generated files from compilation, for example to do


bytecode enhancement/optimization on Java classes.

generate-test-sources Generate any test source code to be included in compilation phase.

process-test-sources Process the test source code, for example, filter any values.

test-compile Compile the test source code into the test destination directory.

process-test-classes Process the generated files from test code file compilation.
test Run tests using a suitable unit testing framework (Junit is one).

prepare-package Perform any operations necessary to prepare a package before the actual
packaging.

package Take the compiled code and package it in its distributable format, such as a
JAR, WAR, or EAR file.

pre-integration-test Perform actions required before integration tests are executed. For example,
setting up the required environment.

integration-test Process and deploy the package if necessary into an environment where
integration tests can be run.

post-integration-test Perform actions required after integration tests have been executed. For
example, cleaning up the environment.

Verify Run any check-ups to verify the package is valid and meets quality criteria.

install Install the package into the local repository, which can be used as a
dependency in other projects locally.

deploy Copies the final package to the remote repository for sharing with other
developers and projects.

3. 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

Maven Repository
• A repository is simply a directory on your machine.
• The project jars, plugins or any other project-related materials are stored here.
• Different types of repositories:
1. Local Repository
2. Central Repository
3. Remote Repository
• Whenever any dependency has to be searched, it is done in repositories. Maven initializes its
search from Local repository, then Central repository and finally in Remote repository.
5.5. Maven Local Repository (.m2)
The local repository of Maven is a folder location on your machine, where all the project
related elements are stored. As soon as the Maven build is executed, Maven automatically
downloads all the dependency jars into the local repository.
By default, maven local repository is user_home/m2 directory.

5.6. Maven Global Repository


When Maven wants to download dependency, it goes to a remote repository. A remote repository is a
repository present on a web server and is widely used to host the internal projects of an organization.

5.7. Group ID, Artifact ID, Snapshot


GroupID
• groupId uniquely identifies project across all projects.
• It starts with a reversed domain name you control.
• This is an Id of project's group which is unique amongst an organization or a project.
• Eg. org.apache.maven, org.apache.commons

Artifact ID
 The artifactId is the id of the project. It specifies the name of the project.
 The groupId is an XML element in the POM.XML file of a Maven project that specifies the id of
the project group.
 In contrast, artifactId is an XML element in the POM.XML of a Maven project that specifies the
id of the project (artifact). Thus, this is the main difference between groupId and artifactId in
Maven.

5.8. Maven Dependencies


• Dependency management is a core feature of Maven.
• Managing dependencies for multi-module projects and applications that consist of hundreds of
modules is possible.
• Maven helps a great deal in defining, creating, and maintaining reproducible builds with well-
defined classpaths and library versions.
Transitive Dependencies
• Maven avoids the need to discover and specify the libraries that your own dependencies
require by including transitive dependencies automatically.
• Achieved by reading the project files of your dependencies from the remote repositories
specified. In general, all dependencies of those projects are used in your project, as are any that
the project inherits from its parents, or from its dependencies, and so on.
• There is no limit to the number of levels that dependencies can be gathered from. A problem
arises only if a cyclic dependency is discovered.

Dependency Mediation
This determines what version of an artifact will be chosen when multiple versions are encountered as
dependencies. Maven picks the "nearest definition".
That is, it uses the version of the closest dependency to your project in the tree of dependencies.
A
├── B
│ └── C
│ └── D 2.0
└── E
└── D 1.0

Dependency Management
• This allows project authors to directly specify the versions of artifacts to be used when they are
encountered in transitive dependencies or in dependencies where no version has been specified.
• In the example in the preceding section a dependency was directly added to A even though it is
not directly used by A. Instead, A can include D as a dependency in its
dependencyManagement section and directly control which version of D is used when, or if, it
is ever referenced.

Dependency Scope
• This allows you to only include dependencies appropriate for the current stage of the build.
• compile
This is the default scope, used if none is specified. Compile dependencies are available in all
classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
• provided
This is much like compile, but indicates you expect the JDK or a container to provide the
dependency at runtime. For example, when building a web application for the Java Enterprise
Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope
provided because the web container provides those classes. A dependency with this scope is
added to the classpath used for compilation and test, but not the runtime classpath. It is not
transitive.

• runtime
This scope indicates that the dependency is not required for compilation, but is for execution.
Maven includes a dependency with this scope in the runtime and test classpaths, but not the
compile classpath.
• test
This scope indicates that the dependency is not required for normal use of the application, and
is only available for the test compilation and execution phases. This scope is not transitive.
Typically this scope is used for test libraries such as JUnit and Mockito. It is also used for non-
test libraries such as Apache Commons IO if those libraries are used in unit tests (src/test/java)
but not in the model code (src/main/java).
• system
This scope is similar to provided except that you have to provide the JAR which contains it
explicitly. The artifact is always available and is not looked up in a repository.
• import
This scope is only supported on a dependency of type pom in the <dependencyManagement>
section. It indicates the dependency is to be replaced with the effective list of dependencies in
the specified POM's <dependencyManagement> section. Since they are replaced, dependencies
with a scope of import do not actually participate in limiting the transitivity of a dependency.

Excluded Dependencies
• If project X depends on project Y, and project Y depends on project Z, the owner of project X
can explicitly exclude project Z as a dependency, using the "exclusion" element.

Optional Dependencies
If project Y depends on project Z, the owner of project Y can mark project Z as an optional
dependency, using the "optional" element. When project X depends on project Y, X will depend only
on Y and not on Y's optional dependency Z. The owner of project X may then explicitly add a
dependency on Z.
5.9. Maven Plugins
• "Maven" is really just a core framework for a collection of Maven Plugins.
• Almost any action that performed on a project is implemented as a Maven plugin.
• Eg. plugins are used to: create jar files, create war files, compile code, unit test code, create
project documentation.
• Plugins are the central feature of Maven that allow for the reuse of common build logic across
multiple projects.
• Build plugins
They execute during the build process and should be configured in the <build/> element of
pom.xml.
• Reporting plugins
They execute during the site generation process and they should be configured in the
<reporting/> element of the pom.xml.

Following is the list of few common plugins –

Plugin Description

Clean Cleans up target after the build. Deletes the target directory.

Compiler Compiles Java source files.

Surefire Runs the JUnit unit tests. Creates test reports.

Jar Builds a JAR file from the current project.

War Builds a WAR file from the current project.

Javadoc Generates Javadoc for the project.

Antrun Runs a set of ant tasks from any phase mentioned of the build.
Demo - Maven project in Eclipse
After opening Eclipse, choose the workspace you want to use.
Complete the following steps:
 Go to the File option
 In the drop-down menu, select New
 Select the Project option
If you want to create a Java project, you can select the “Java Project” option. Since we are not creating
a Java project specifically, we have chosen the “Project” option.

The dialog box that appears on the screen will display different types of projects.
 Select the Maven Project option
 Click on Next
A dialog box will appear. Select the default workspace.
 Click on “Next”
Several Group IDs, Artifact IDs, and Versions will then appear.
 Select a plugin there and click on “Next”

In the next dialog box that appears, you’ll complete the following steps:
 Enter the Group ID
“com.simplilearn”
 Enter the Artifact ID
“mavenproject”
 The version will appear on the screen
These items can all be modified at a later time if needed.
 Click on “Finish”
The project is now created.
 Open the pom.xml file
You can see all the basic information that you have entered on the screen, such as the Artifact ID,
Group ID, etc.
You can see the junit dependencies have been added.
This process takes place by default in Eclipse. There will also be some by default test cases.

There you can find AppTest.java to be a default test case.


When you click on that, you can see the test cases written in JUnit on your Eclipse screen.
When it comes to adding more test cases, it will depend on the user, but these test cases and
commands can easily be added in the workspace.
If we try to remove certain dependencies from our file, we will receive error messages. To
troubleshoot this, complete the following steps:
 Go to another tab: mavenproject/pom.xml
 Delete any dependencies
 Save the file
Immediately, there will be several error messages in the AppTest.java.

Return to the previous screen and undo the deletion. The errors that occurred will disappear.
The demo shows the relationship between the dependencies and the Eclipse. When a Maven project is
selected, all such dependencies are automatically downloaded. If any dependencies are not present,
Eclipse will show errors.

Advantages of Maven:

 Helps manage all the processes, such as building, documentation, releasing, and distribution in
project management

 Simplifies the process of project building

 Increases the performance of the project and the building process

 The task of downloading Jar files and other dependencies is done automatically

 Provides easy access to all the required information

 Makes it easy for the developer to build a project in different environments without worrying about
the dependencies, processes, etc.

 In Maven, it’s easy to add new dependencies by writing the dependency code in the pom file

Drawbacks of Maven:

 Maven requires installation in the working system and the Maven plug-in for the IDE.

 If the Maven code for an existing dependency is unavailable, you cannot add that dependency using
Maven itself

You might also like