0% found this document useful (0 votes)
11 views130 pages

Devops Module 2

The document provides a comprehensive overview of Apache Maven, including its installation, objectives, key features, and the Project Object Model (POM). It emphasizes Maven's role in simplifying the build process for Java projects, managing dependencies, and promoting best practices. Additionally, it covers project aggregation and inheritance, highlighting how Maven facilitates project organization and workflow management.

Uploaded by

bhuvanesh121314
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views130 pages

Devops Module 2

The document provides a comprehensive overview of Apache Maven, including its installation, objectives, key features, and the Project Object Model (POM). It emphasizes Maven's role in simplifying the build process for Java projects, managing dependencies, and promoting best practices. Additionally, it covers project aggregation and inheritance, highlighting how Maven facilitates project organization and workflow management.

Uploaded by

bhuvanesh121314
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

• Introduction, Installation of Maven, POM files,

Maven Build lifecycle, Build phases(compile


build,test, package) Maven Profiles, Maven
repositories(local, central, global),Maven
plugins,
MavencreateandbuildArtificats,Dependencym
anagement,InstallationofGradle,Understandbu
ildusingGradle
Introduction
• Maven, a word denotes accumulator of knowledge.
• It is to simplify the build processes in the Jakarta
Turbine project.
• Actually, there were several projects, each with their
own Ant build files, (build.xml, a xml formatted build
file) that were all slightly different.
• A standard way to build the projects, an easy way to
publish project information, and a way to share JARs
across several projects is required.
• The result is a tool, called Maven, that can now be
used for building and managing any Java-based
project
Mavens Objective
• Maven's primary goal is to allow a developer to
organize and a build a Java project in the shortest
period of time using the following
• Making the build process easy - abstract
underlying complexities from developers
• Providing a uniform build system- Project Object
Model (POM ) and other Plugins
• Providing quality project information-only useful
project information is provided.
• Encouraging better development practices –
gather current principles for project development.
Mavens Objective
• Maven's primary goal is to allow a developer to
organize and a build a Java project in the shortest
period of time using the following
• Making the build process easy - abstract
underlying complexities from developers
• Providing a uniform build system- Project Object
Model (POM ) and other Plugins
• Providing quality project information-only useful
project information is provided.
• Encouraging better development practices –
gather current principles for project development.
Objectives
• Maven also assists in project workflow such as release and
issue management.
• Maven also suggests some guidelines on how to layout
your project's directory structure. Once you learn the
layout, you can easily navigate other projects that use
Maven.
• While Maven takes an opinionated approach to project
layout, some projects may not fit with this structure for
historical reasons. While Maven is designed to be flexible
to the needs of different projects, it cannot cater to every
situation without compromising its objectives.
• If your project has an unusual build structure that cannot
be reorganized, you may have to forgo some features or
the use of Maven altogether.
Key Features
• Simple project setup that follows best practices - get a new
project or module started in seconds-
• Consistent usage across all projects - means no ramp up time
for new developers coming onto a project-
• Superior dependency management including automatic
updating, dependency closures (also known as transitive
dependencies)-
• Able to easily work with multiple projects at the same time-
• A large and growing repository of libraries and metadata to use
out of the box
• Extensible, with the ability to easily write plugins in Java or
scripting languages-
Key Features
• Instant access to new features with little or no extra
configuration.
• Ant tasks for dependency management and deployment
outside of Maven-
• Model based builds: Maven is able to build any number of
projects into predefined output types such as a JAR, WAR, or
distribution based on metadata about the project, without the
need to do any scripting in most cases.
• Coherent site of project information: Using the same metadata
as for the build process, Maven is able to generate a website or
PDF including any documentation you care to add, and adds to
that standard reports about the state of development of the
project. Examples of this information can be seen at the bottom
of the left-hand navigation of this site under the “Project
Information” and “Project Reports” submenus.
Key Features
• Release management and distribution publication: Without much
additional configuration, Maven will integrate with source
control system (such as Subversion or Git) and manage the
release of a project based on a certain tag. It can also publish this
to a distribution location for use by other projects. Maven is able
to publish individual outputs such as a JAR, an archive including
other dependencies and documentation, or as a source
distribution.
• Dependency management: Maven encourages the use of a
central repository of JARs and other dependencies. Maven comes
with a mechanism that your project's clients can use to
download any JARs required for building your project from a
central JAR repository. This allows users of Maven to reuse JARs
across projects and encourages communication between projects
to ensure that backward compatibility issues are dealt with.
Installation
• Installation
• Apache Maven can be installed by most package
managers, or manually by downloading the archive
and adding it to your path.
• Prerequisites
• You need a Java Development Kit (JDK) installed.
Either set the JAVA_HOME environment variable to
the path of your JDK installation or have
the java executable on your PATH.
• The current stable version 3.9.11 requires JDK 8+,
but any recent version will work just fine.
• Binary distribution
• To install Apache Maven, extract the archive and add its
bin directory to the PATH. This works on any operating
system, but setting the path and environment variables
depends on the OS.
• Detailed steps are:
• Download the Apache Maven binary distribution archive.
• Extract the distribution archive in any directory. Use unzip
apache-maven-3.9.11-bin.zip or tar xzvf apache-maven-
3.9.11-bin.tar.gz depending on the archive.
• Add the bin directory of the created directory apache-
maven-3.9.11 to the PATH environment variable
• Confirm with mvn -v in a new shell
• The result should look similar to:
• Apache Maven 3.9.11
(3e54c93a704957b63ee3494413a2b544fd3d825b)
• Maven home: /opt/apache-maven-3.9.11
• Java version: 1.8.0_45, vendor: Oracle Corporation
• Java home: /Library/Java/JavaVirtualMachines/
jdk1.8.0_45.jdk/Contents/Home/jre
• Default locale: en_US, platform encoding: UTF-8
• OS name: "mac os x", version: "10.8.5", arch:
"x86_64", family: "mac"
• That’s it! Maven is now installed
Downloading Apache Maven 3.9.11
• System Requirements
– Java Development Kit (JDK)
– Maven 3.9+ requires JDK 8 or above to execute
• Memory
• No minimum requirement
• Disk
• Approximately 10MB is required for the Maven installation
The size of your local repository will vary depending on usage
but expect at least 500MB.
• Operating System
• No minimum requirement.
• Start up scripts are included as shell scripts (and Windows
batch files the public KEYS used by the Apache Maven
• Files
• Maven is distributed in several formats.
• Simply pick a ready-made binary distribution archive and follow the
installation instructions.
• Use a source archive to build Maven on your ownf.
• In order to guard against corrupted downloads/installations, it is highly
recommended to verify the signature of the release bundles against the
public KEYS used by the Apache Maven developers.
• All current release sources (plugins
, shared libraries,...) available at
https://downloads.apache.org/maven/
• Maven Daemon
• Apache Maven Daemon (mvnd) is available as
a separate download. In order to guard
against corrupted downloads/installations, it is
highly recommended to verify the signature of
the release bundles against the public KEYS
used by the Apache Maven developers
Running Apache Maven
• The syntax for running Maven is as follows:
• mvn [options] [<goal(s)>] [<phase(s)>] All available
options are documented in the built-in help that you can
access with
• mvn -h
• The typical invocation for building a Maven project uses
a Maven lifecycle phase. E.g.
• mvn verify
• The built-in lifecycles and their most used phases, in
order, are:
• clean - clean
• default -
validate, compile, test, package, verify, install, deploy
• site - site, site-deploy
• A fresh build of a project generating all packaged outputs and the
documentation site and deploying it to a repository manager could be
done with
• mvn clean deploy site-deploy
• Just creating the package and installing it in the local repository for re-
use from other projects can be done with
• mvn install
• And if you don't expect to re-use from other projects, use
• mvn verify
• This is the most common build invocation for a Maven project.
• When not working with a project, and in some other use cases, want to
invoke a specific task implemented by a part of Maven - this is called
a goal of a plugin.
• E.g.:
• mvn archetype:generate
or
• mvn checkstyle:check
• There are many different plugins available and they all implement
different goals.
Project Object Model (POM)
• A Project Object Model or POM is the fundamental unit of
work in Maven. It is an XML file that contains information
about the project and configuration details used by Maven to
build the project. It contains default values for most projects.
– build directory, which is target;
– the source directory, which is src/main/java;
– the test source directory, which is src/test/java; and so on.
• When executing a task or goal, Maven looks for the POM in
the current directory. It reads the POM, gets the needed
configuration information, then executes the goal.
• Some of the configuration that can be specified in the POM
are the project dependencies, the plugins or goals that can be
executed, the build profiles, and so on. Other information
such as the project version, description, developers, mailing
lists and such can also be specified.
• Types of POM
– Super POM
– Minimal POM
• Super POM
• The Super POM is Maven's default POM. All POMs extend
the Super POM unless explicitly set, meaning the
configuration specified in the Super POM is inherited by
the POMs you created for your projects.
• Minimal POM
• The minimum requirement for a POM are the following:
A POM requires that its groupId, artifactId, and version be
configured. These three values form the project's fully qualified
artifact name. This is in the form of
<groupId>:<artifactId>:<version>. As for the example above, its
fully qualified artifact name is “com.mycompany.app:my-app:1”
Example to define another artifact
• <project xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-module</artifactId>
• <version>1</version>
• </project>
• Directory structure is as follows
• . |-- my-module | `
• -- pom.xml // pom for my module
• `-- pom.xml // pom for super
• Project Inheritance
• Elements in the POM that are merged are the
following:
– dependencies
– developers and contributors
– plugin lists (including reports)
– plugin executions with matching ids
– plugin configuration
– resources
• The Super POM is one example of project inheritance,
however you can also introduce your own parent
POMs by specifying the parent element in the POM,
as demonstrated in the following examples.
Example for super as parent for new artifact
• <project xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <parent>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-app</artifactId>
• <version>1</version>
• </parent>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-module</artifactId>
• <version>1</version>
• </project>
• Usage
• our module can now inherit some of the properties of our parent POM.
Example for groupid and version is common

• <project xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <parent>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-app</artifactId>
• <version>1</version>
• </parent>
• <artifactId>my-module</artifactId>
• </project>
• The Scenario
• If the parent project was already installed in our
local repository or was in that specific directory
structure (parent pom.xml is one directory
higher than that of the module's pom.xml).
• But what happened if the parent is not yet
installed and directory structure is as follows
• |-- my-module
• | ` -- pom.xml `
• -- parent
• `-- pom.xml
• <project
xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <parent>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-app</artifactId>
• <version>1</version>
• <relativePath>../parent/pom.xml</relativePath>
• </parent>
• <artifactId>my-module</artifactId>
• </project>
Project Aggregation
• Project Aggregation is similar to Project Inheritance. But
instead of specifying the parent POM from the module,
it specifies the modules from the parent POM.
• By doing so, the parent project now knows its modules,
and if a Maven command is invoked against the parent
project, that Maven command will then be executed to
the parent's modules as well.
• To do Project Aggregation, you must do the following:
• Change the parent POMs packaging to the value “pom”.
• Specify in the parent POM the directories of its modules
(children POMs).
Aggregate my-module into my-app
• <project
xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-app</artifactId>
• <version>1</version>
• <packaging>pom</packaging>
• <modules>
• <module>my-module</module>
• </modules>
• </project>
• Directory structure
• |-- my-module
• | `-- pom.xml `
• -- pom.xml
• The packaging section and the modules sections
were added. For the packaging, its value was set
to “pom”, and for the modules section, we have
the element <module>my-module</module>.
The value of <module> is the relative path from
the com.mycompany.app:my-app:1 to
com.mycompany.app:my-module:1's POM
• |-- my-module
• | `-- pom.xml
• `-- parent
• `-- pom.xml
• <project xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <groupId>com.mycompany.app</groupId>
• <artifactId>my-app</artifactId>
• <version>1</version>
• <packaging>pom</packaging>
• <modules>
• <module>../my-module</module>
• </modules>
• </project>
• Project Inheritance vs Project Aggregation
• If you have several Maven projects, and they all have similar
configurations, you can refactor your projects by pulling out those
similar configurations and making a parent project. Thus, all you have
to do is to let your Maven projects inherit that parent project, and
those configurations would then be applied to all of them.
• And if you have a group of projects that are built or processed
together, you can create a parent project and have that parent project
declare those projects as its modules. By doing so, you'd only have to
build the parent and the rest will follow.
• But of course, you can have both Project Inheritance and Project
Aggregation. Meaning, you can have your modules specify a parent
project, and at the same time, have that parent project specify those
Maven projects as its modules. You'd just have to apply all three rules:
• Specify in every child POM who their parent POM is.
• Change the parent POMs packaging to the value “pom” .
• Specify in the parent POM the directories of its modules (children
POMs)
Project Interpolation and Variables
• There are circumstances where you will need to use the
same value in several different locations. To assist in
ensuring the value is only specified once, Maven allows
you to use both your own and pre-defined variables in the
POM.
• For example, to access the project.version variable, you
would reference it like so:
• <version>${project.version}</version>
• One factor to note is that these variables are
processed after inheritance as outlined above. This means
that if a parent project uses a variable, then its definition
in the child, not the parent, will be the one eventually
used.
• Available Variables
• Project Model Variables
• Any field of the model that is a single value element can be
referenced as a variable. For example, ${project.groupId}, $
{project.version}, ${project.build.sourceDirectory} and so on.
• These variables are all referenced by the prefix “project.”. You
may also see references with pom. as the prefix, or the prefix
omitted entirely - these forms are now deprecated and should
not be used.
• Special Variables
• project.basedirThe directory that the current project resides in.
• project.baseUriThe directory that the current project resides in,
represented as an URI.
• maven.build.timestampThe timestamp that denotes the start of
the build (UTC). Since Maven 2.1.0-M1
• <project
xmlns="http://maven.apache.org/POM/4.0.0">
• ...
• <properties>
• <maven.build.timestamp.format>yyyy-MM-
dd'T'HH:mm:ss'Z'</maven.build.timestamp.format>
• </properties>
• ...
• </project>
• <project xmlns="http://maven.apache.org/POM/4.0.0">
• ...
• <properties>
• <mavenVersion>3.0</mavenVersion>
• </properties>
• <dependencies>
• <dependency>
• <groupId>org.apache.maven</groupId>
• <artifactId>maven-artifact</artifactId>
• <version>${mavenVersion}</version>
• </dependency>
• <dependency>
• <groupId>org.apache.maven</groupId>
• <artifactId>maven-core</artifactId>
• <version>${mavenVersion}</version>
• </dependency>
• </dependencies>
• ...
• </project>
MAVEN BUILD LIFECYCLE
• Maven Build Lifecycle is a fundamental
concept in Maven that defines a sequence of
phases and goals to be executed for managing
the entire build process, from compilation to
deployment.
• There are three primary types of build lifecycles in
Maven:
• Default Lifecycle: Handles the standard deployment
process of the project, from compiling the code to
packaging and installing it.
• Clean Lifecycle: Manages the cleaning process by
removing artifacts from previous builds to ensure a
fresh build environment.
• Site Lifecycle: Deals with generating and deploying the
project's site documentation, such as project reports
and other documentation.
• Each lifecycle consists of several phases, and when you
execute a phase, all preceding phases are also executed.
BUILD LIFE CYCLE
• 1. Default Lifecycle
• The Default Lifecycle is the most commonly used lifecycle, focusing on
the build process from validation to deployment.
• Phases in this lifecycle are as follows:
• Validate Phase: Checks the project configuration to ensure all
necessary information is present and valid.
• Compile Phase: Compiles the source code of the project.
• Test Phase: Runs unit tests using a testing framework to ensure the
code works as expected.
• Package Phase: Packages the compiled code into a JAR, WAR, or other
artifact format.
• Verify Phase: Performs additional checks on the packaged code to
ensure it is valid.
• Install Phase: Installs the packaged artifact into the local repository
for use as a dependency in other projects.
• Deploy Phase: Deploys the packaged artifact to a remote repository
for sharing with other developers or teams.
• 2. Clean Lifecycle
• The Clean Lifecycle is designed for cleaning the project, ensuring
that artifacts generated from previous builds are removed before
starting the new build process.
• Phases in the Clean Lifecycle:
• pre-clean: Executes processes before cleaning.
• clean: Removes files generated by the previous build.
• post-clean: Executes processes after cleaning.
• 3. Site Lifecycle
• The Site Lifecycle is responsible for generating and deploying
project documentation.
• pre-site: Executes processes before generating site
documentation.
• site: Generates the site documentation.
• post-site: Executes processes after generating site documentation.
• site-deploy: Deploys the generated site documentation to a web
server.
Example
• <?xml version="1.0" encoding="UTF-8"?> <project
xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema
-instance"
xsi:schemaLocation="https://maven.apache.org/P
OM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
• <groupId>org.springframework.boot</
groupId> <artifactId>spring-boot-starter-
parent</artifactId> <version>3.2.6</version>
<relativePath /> <!-- lookup parent from
repository --> </parent>
<groupId>com.app</groupId>
<artifactId>mavenbuild</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mavenbuild</name>
<description>Spring Reactive</description>
• <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> </dependency>
</dependencies>
• <reporting> <plugins> <!-- Javadoc Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupI
d>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.1</version> <configuration>
<source>17</source> </configuration>
</plugin> </plugins> </reporting>
• <build> <plugins> <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version> <configuration>
<source>17</source> <target>17</target>
</configuration> </plugin> </plugins> </build>
</project>
mvn validate
mvn compile
• Ex 2 : <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> </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>
• C:\MVN\project>mvn post-clean Maven will start processing and displaying
all the phases of clean life cycle.
• C:\MVN>mvn post-clean

• Output

• [INFO] Scanning for projects... [INFO] [INFO] ----------------<


com.companyname.projectgroup:project >---------------- [INFO] Building
project 1.0 [INFO] --------------------------------[ jar ]---------------------------------
[INFO] [INFO] --- maven-antrun-plugin:1.1:run (id.pre-clean) @ project ---
[INFO] Executing tasks [echo] pre-clean phase [INFO] Executed tasks [INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project --- [INFO]
[INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project --- [INFO]
Executing tasks [echo] clean phase [INFO] Executed tasks [INFO] [INFO] ---
maven-antrun-plugin:1.1:run (id.post-clean) @ project --- [INFO] Executing
tasks [echo] post-clean phase [INFO] Executed tasks [INFO]
------------------------------------------------------------------------ [INFO] BUILD
SUCCESS [INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.740 s [INFO] Finished at: 2021-12-10T20:03:53+05:30
[INFO] ------------------------------------------------------------------------ C:\MVN>
MAVEN PROFILES
• Maven profiles are a powerful feature in
Apache Maven that allow customization of the
build process for different environments or
scenarios without modifying the
core pom.xml file.
• They provide a mechanism to define
alternative sets of configuration values that
can override or extend the default settings.
• Profiles enable adapting a project's build to varying
conditions, such as:
• Environment-specific configurations: Using different
database connections, API keys, or server URLs for
development, testing, and production.
• Platform-specific adjustments: Modifying build settings
based on the operating system (Windows, Linux, macOS).
• Selective dependency inclusion: Adding or excluding
libraries based on the build's purpose (e.g., including
testing frameworks only for CI builds).
• Controlled build behavior: Activating or deactivating
specific plugins or goals, such as generating reports only
during certain build stages.
• Definition:
• Profiles are defined within the <profiles> element
in the pom.xml file. Each profile is given a unique
identifier using the <id> element. Inside a profile,
you can specify various configurations, including:
• <dependencies>
• <plugins>
• <properties>
• <repositories>
• <build> elements
like resources, testResources, finalName, etc.
• What are the different types of profile? Where is each defined?
• Per Project
• - Defined in the POM itself (pom.xml).
• Per User
• - Defined in the Maven-settings (%USER_HOME%/.m2/settings.xml).
• Global
• - Defined in the global Maven-settings
(${maven.home}/conf/settings.xml).
• Profile Inheritance
• The profiles are not inherited as other POM elements by child
POMs. Instead they are resolved very early by the
Maven Model Builder and only the effects of active profiles are
inherited (e.g. the plugins defined in the profile). That also leads to
the fact that implicit profile activation only has an effect on the
surrounding profile container but never on any other profile (even if
it has the same id).
Type of profile activation
• A profile can be activated in several ways:
• Explicitly
• Implicitly
– Based on OS
– Based on system properties
– Based on presence of files
• Explicit profile activation
• Profiles can be explicitly specified using the -
P command line flag.
• This flag is followed by a comma-delimited list
of profile IDs to use.
• The profile(s) specified in the option are
activated in addition to any profiles which are
activated by their activation configuration or
the <activeProfiles> section in settings.xml.
From Maven 4 onward, Maven will refuse to
activate or deactivate a profile that cannot be
resolved. To prevent this, prefix the profile
identifier with an ?, marking it as optional:
• mvn groupId:artifactId:goal -P profile-1,profile-2,
• ?profile-3 Profiles can be activated in the Maven settings, via
the <activeProfiles> section. This section takes a list
of <activeProfile> elements, each containing a profile-id
inside.
• <settings>
• ...
• <activeProfiles>
• <activeProfile>profile-1</activeProfile>
• </activeProfiles>
• ...
• </settings>
• Profiles listed in the <activeProfiles> tag would be activated
by default every time a project use it.
• Profiles can also be active by default using a configuration like the
following in a POM:
• <profiles>
• <profile>
• <id>profile-1</id>
• <activation>
• <activeByDefault>true</activeByDefault>
• </activation>
• ...
• </profile>
• </profiles>
• This profile will automatically be active for all builds unless another
profile in the same POM is activated using one of the previously
described methods.
• All profiles that are active by default are automatically deactivated
when a profile in the POM is activated on the command line or
through its activation config.
• Implicit profile activation
• Profiles can be automatically triggered based on the detected state of the
build environment. These triggers are specified via an <activation> section in
the profile itself.
• Currently, this detection is limited to JDK version matching, operating system
matching or the presence/the value of a system property. The implicit profile
activation always only refers to the container profile Here are some
examples.
• JDK
• The following configuration will trigger the profile when the JDK's
version starts with “1.4” (eg. “1.4.0_08”, “1.4.2_07”, “1.4”), in particular
it won't be active for newer versions like “1.8” or “11”:
• <profiles>
• <profile>
• <activation>
• <jdk>1.4</jdk>
• </activation>
• ...
• </profile>
• Ranges can also be used. Range values must start with
either [ or (. Otherwise, the value is interpreted as a prefix.
The following honours versions 1.3, 1.4 and 1.5.
• <profiles>
• <profile>
• <activation>
• <jdk>[1.3,1.6)</jdk>
• </activation>
• ...
• </profile>
• </profiles>
• OS
• This next one will activate based on the detected operating system.
• <profiles>
• <profile>
• <activation>
• <os>
• <name>Windows XP</name>
• <family>Windows</family>
• <arch>x86</arch>
• <version>5.1.2600</version>
• </os>
• </activation>
• ...
• </profile>
• </profiles>
• The values are interpreted as Strings and are matched
against the Java System properties
os.name, os.arch, os.version and the family being derived
from those.
• Each value can be prefixed with ! to negate the matching.
The values match if they are (not) equal to the actual
String value (case insensitive). All given OS conditions must
match for the profile to be considered for activation.
• Since Maven 3.9.7 the value for version may be prefixed
with regex:. In that case regular pattern matching is
applied for the version matching and applied against
the lower case os.version value.
• The actual OS values which need to match the given values
are emitted when executing mvn –version.
• Property
• The profile below will be activated when the system
property “debug” is specified with any value:
• <profiles>
• <profile>
• <activation>
• <property>
• <name>debug</name>
• </property>
• </activation>
• ...
• </profile>
• </profiles>
• <profiles>
• <profile>
• <activation>
• <property>
• <name>!debug</name>
• </property>
• </activation>
• ...
• </profile>
• </profiles>
• The following profile will be activated when the system property
“debug” is defined with no value, or is defined with the value “true”.
• <profiles>
• <profile>
• <activation>
• <property>
• <name>debug</name>
• <value>true</value>
• </property>
• </activation>
• ...
• </profile>
• </profiles>
• To run
• mvn groupId:artifactId:goal -Ddebug mvn groupId:artifactId:goal -
Ddebug=true
MAVEN REPOSITORIES(Artifact)
• A repository in Maven holds build artifacts of varying
types.
– Local and
– Remote
– The local repository is a directory on the computer where
Maven runs. It caches remote downloads and contains
temporary build artifacts that you have not yet released.
– remote repositories refer to any other type of repository,
accessed by a variety of protocols such
as file:// and https://.
• Is a remote repository set up by a third party to provide their
artifacts for downloading (for example, repo.maven.apache.org
).
• Other “remote” repositories may be internal repositories set up
on a file or HTTP server within your company, used to share
• Using Mirrors for the Central Repository
• There are several official Central repositories
geographically distributed. You can make
changes to your settings.xml file to use one or
more mirrors
Using 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.
• Maven local repository by default get created by Maven
in %USER_HOME% directory. To override the default
location, mention another path in Maven settings.xml file
available at %M2_HOME%\conf directory
• <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>
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 −
https://repo1.maven.org/maven2/
• Key concepts of Central repository are as follows −
– This repository is managed by Maven community.
– It is not required to be configured.
– It requires internet access to be searched.
• To browse the content of central maven repository, maven
community has provided a URL −
https://search.maven.org/#browse. Using this library, a
developer can search all the available libraries in central
repository.
• Remote Repositories
• Remote repositories, they are used for both downloading and
uploading .
• 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.
• <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</gro
upId> <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>
• Maven Dependency Search Sequence
• When we execute Maven build commands, Maven starts
looking for dependency libraries in the following sequence
• Step 1 − Search dependency in local repository, if not found,
move to step 2 else perform the further processing.
• Step 2 − Search dependency in central repository, if not found
and remote repository/repositories is/are mentioned then
move to step 4. Else it is downloaded to local repository for
future reference.
• Step 3 − If a remote repository has not been mentioned, Maven
simply stops the processing and throws error (Unable to find
dependency).
• Step 4 − Search dependency in remote repository or
repositories, if found then it is downloaded to local repository
for future reference. Otherwise, Maven stops processing and
throws error (Unable to find dependency).
• Building Offline
• use the offline switch on the CLI:
• mvn -o package
• Many plugins honor the offline setting and do
not perform any operations that connect to
the internet.
• Uploading to a Remote Repository
• While this is possible for any type of remote
repository, you must have the permission to
do so. To have someone upload to the Central
Maven repository, see Repository Center.
• Requirements
• releases: Only releases can be uploaded to the Central
Repository. A release can only depend on other files
already released and available in the repository. The
Central Repository will not change or replace a release
after it is published.
• javadoc and sources for IDE lookup
• PGP (Pretty Good Privacy) signature for encrypting data
• minimum POM information: Maven Central requires
that a POM contain certain minimal information before it
will publish a release.
• coordinates: Picking the appropriate coordinates for your
project is important, particularly the details about group
ID and domain ownership.
• Basic sample
• <project
xmlns="http://maven.apache.org/POM/4.0.0">
• <modelVersion>4.0.0</modelVersion>
• <groupId>org.apache.maven</groupId>
• <artifactId>maven</artifactId>
• <version>2.0</version>
• <packaging>jar</packaging>
• <name>Maven core</name>
• <description>The maven main core project
description</description>
• <url>https://maven.apache.org</url>
• <licenses>
• <license>
• <name>Apache License, Version 2.0</name>
• <url>http://www.apache.org/licenses/LICENSE-
2.0.txt</url>
• <distribution>repo</distribution>
• </license>
• </licenses>
• <scm>
• <url>https://svn.apache.org/viewvc/maven</
url>
• </scm>
• <dependencies>
• <dependency>
• <groupId>...</groupId>
• <artifactId>...</artifactId>
• <version>...</version>
• </dependency>
• ...
• </dependencies>
• <!--
• NOT RECOMMENDED:
• <repositories></repositories>
• <pluginRepositories></pluginRepositories>
• -->
• </project>
Maven plugins
• Maven is actually a plugin execution framework
where every task is actually done by plugins.
Maven Plugins are generally used to −
• create jar file
• create war file
• compile code files
• unit testing of code
• create project documentation
• create project reports
• A plugin generally provides a set of goals,
which can be executed using the following
syntax −
• mvn [plugin-name]:[goal-name]
• For example, a Java project can be compiled
with the maven-compiler-plugin's compile-
goal by running the following command.
• mvn compiler:compile
• Types
• 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.
• Commonly used Plugins
• 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.
• 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</groupI
d> <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.clean</id>
• <phase>clean</phase>
• <goals>
• <goal>run</goal>
• </goals>
• <configuration>
• <tasks>
• <echo>clean phase</echo>
• </tasks>
• </configuration>
• </execution>
• </executions>
• </plugin>
• </plugins>
• </build> </project>
• Te 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.
• C:\MVN>mvn clean
• [INFO] Scanning for projects...
• [INFO]
• [INFO] ----------------< com.companyname.projectgroup:project >----------------
• [INFO] Building project 1.0
• [INFO] --------------------------------[ jar ]--------------------------------- [INFO]
• [INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ project --- [INFO] Deleting
C:\MVN\target
• [INFO]
• [INFO] --- maven-antrun-plugin:1.1:run (id.clean) @ project ---
• [INFO] Executing tasks [echo] clean phase [INFO] Executed tasks
• [INFO] ------------------------------------------------------------------------
• [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
• [INFO] Total time: 1.266 s
• [INFO] Finished at: 2021-12-13T13:58:10+05:30
• [INFO] ------------------------------------------------------------------------
• C:\MVN> The above example illustrates the following key
concepts −
• Plugins are specified in pom.xml using plugins element.
• Each plugin can have multiple goals.
• You can define phase from where plugin should starts its
processing using its phase element. We've used clean phase.
• You can configure tasks to be executed by binding them to
goals of plugin. We've bound echo task with run goal
of maven-antrun-plugin.
• Maven will then download the plugin if not available in local
repository and start its processing.
Maven-Create Project
• Maven uses archetype plugins to create projects. To create
a simple java application, we'll use maven-archetype-
quickstart plugin. In example below, we'll create a maven
based java application project in C:\MVN folder.
• Let's open the command console, go to the C:\MVN
directory and execute the following mvn command. Make
sure that C:\MVN directory is empty before running the
command.
• C:\MVN>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.
• consumerBanking
• contains src folder and pom.xml
• src/main/java
• contains java code files under the package
structure (com/companyName/bank).
• src/main/test
• contains test java code files under the package
structure (com/companyName/bank).
• src/main/resources
• it contains images/properties files (In above
example, we need to create this structure
manually).
• C:\MVN\consumerBanking\src\main\java\com\
companyname\bank folder, you will see
App.java.
• package com.companyname.bank;
• public class App
• {
public static void main( String[] args )
• {
• System.out.println( "Hello World!" );
• }
• }
• C:\MVN\consumerBanking\src\test\java\com\
companyname\bank folder to see AppTest.java.
• package com.companyname.bank;
• import junit.framework.Test;
• import junit.framework.TestCase;
• import junit.framework.TestSuite;
• public class AppTest extends TestCase
• {
• public AppTest( String testName )
• { super( testName ); }
• public static Test suite() {
• return new TestSuite( AppTest.class ); }
• public void testApp()
• { assertTrue( true ); } }
Build and test the project
1. Go to C:/MVN directory where you've
created your java applications .
2. Open consumerBanking folder.
3. POM.xml with the following contents.
4. Update it to reflect the current java version.
• <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>
• <properties> <maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target> </properties>
• <dependencies>
• <dependency>
• <groupId>junit</groupId>
• <artifactId>junit</artifactId>
• <version>3.8.1</version>
• </dependency>
• </dependencies>
• </project>
• Maven adds a source file App.java and a test
file AppTest.java in its default directory
structure.
• Let's open the command console, go the C:\
MVN\consumerBanking directory and execute
the following mvn command.
• C:\MVN\consumerBanking>mvn clean
package
• Maven will start building the project.
Basic concept
• We give maven two goals, first to clean the target directory
(clean) and then package the project build output as jar
(package).
• Packaged jar is available in consumerBanking\target folder
as consumerBanking-1.0-SNAPSHOT.jar.
• Test reports are available in consumerBanking\target\
surefire-reports folder.
• Maven compiles the source code file(s) and then tests the
source code file(s).
• Then Maven runs the test cases.
• Finally, Maven creates the package.
• Now open the command console, go the C:\
MVN\consumerBanking\target\classes
directory and execute the following java
command.
• >java com.companyname.bank.App You will
see the result as follows −
• Hello World!
Add additional source file
• C:\MVN\consumerBanking\src\main\java\
com\companyname\bank folder, create Util
class in it as Util.java.
• package com.companyname.bank;
• public class Util
• {
• public static void printMessage(String
message)
• { System.out.println(message); } }
• package com.companyname.bank;
• public class App
• {
• public static void main( String[] args )
• {
• Util.printMessage("Hello World!");
• }
• }
• execute the following mvn command.
• >mvn clean compile
• After Maven build is successful, go to the C:\
MVN\consumerBanking\target\classes directory
and execute the following java command.
• >java -cp com.companyname.bank.App
• You will see the result as follows −
• Hello World!
Dependency management
• One of the core features of Maven is
Dependency Management.
• Managing dependencies is a difficult task once
we've to deal with multi-module projects
(consisting of hundreds of modules/sub-
projects).
• Maven provides a high degree of control to
manage such scenarios.
Transitive Dependencies Discovery
• It is pretty often a case, when a library, say A,
depends upon other library, say B. In case
another project C wants to use A, then that
project requires to use library B too.
• 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.
Transitive Dependencies Discovery
• 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 mediation
• Determines what version of a dependency is
to be used when multiple versions of an
artifact are encountered. If two dependency
versions are at the same depth in the
dependency tree, the first declared
dependency will be used.
• Dependency management
• Directly specify the versions of artifacts to be
used when they are encountered in transitive
dependencies. For an example project C can
include B as a dependency in its dependency
Management section and directly control
which version of B is to be used when it is ever
referenced.
• Dependency scope
• Includes dependencies as per the current
stage of the build.
• Excluded dependencies
• Any transitive dependency can be excluded
using "exclusion" element. As example, A
depends upon B and B depends upon C, then
A can mark C as excluded.
• Optional dependencies
• Any transitive dependency can be marked as
optional using "optional" element. As
example, A depends upon B and B depends
upon C. Now B marked C as optional. Then A
will not use C.
Dependency Scope
• compile
• This scope indicates that dependency is available in
classpath of project. It is default scope.
• provided
• This scope indicates that dependency is to be
provided by JDK or web-Server/Container at runtime.
• runtime
• This scope indicates that dependency is not required
for compilation, but is required during execution.
Dependency Scope
• test
• This scope indicates that the dependency is only
available for the test compilation and execution phases.
• system
• This scope indicates that you have to provide the
system path.
• import
• This scope is only used when dependency is of type
pom. This scope indicates that the specified POM
should be replaced with the dependencies in that
POM's <dependencyManagement> section.
• 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.
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>
• <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>
• <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>
Root
• <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> <dependencies>
Root
• <dependencies>
• <dependency>
• <groupId>com.companyname.groupname3</
groupId>
• <artifactId>Lib3</artifactId>
• <version>1.1</version>
• </dependency> </dependencies> </project>

You might also like