0% found this document useful (0 votes)
106 views

Maven Tutorial - Learn Code With Durgesh

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

Maven Tutorial - Learn Code With Durgesh

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

Maven Tutorial

Spring Boot+ Microservices Categories


(Live batch) ×
started from 2nd July!! Registrations
Open!!

Click Here

Introduction to Maven

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 1 of 43
:
What is Maven?
LCWD
Maven is a build automation tool
primarily used for Java projects. It
addresses two main aspects of building
software: dependency management
and project build lifecycle management.
It simpliMes the build process by
managing dependencies, compiling
source code, packaging it into a
deliverable (such as a JAR Mle), and
deploying it to a repository.
Maven is based on the concept of a
Project Object Model (POM), which is a
central piece of information that
manages a project’s build, reporting,
and documentation.

History and Evolution


of Maven
Maven was developed by the Apache
Software Foundation and released in
2004.
It was created to address the problems
with Apache Ant, a popular build tool at
the time. Maven was designed to
simplify the build process, provide a
uniform build system, and offer project
information that could be shared
among developers.
Over the years, Maven has become one
of the most widely used build tools in
the Java ecosystem.

Setting Up Maven

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 2 of 43
:
This section will guide your trainees
through installing and setting up Maven
on their machines and integrating it with
popular IDEs like IntelliJ IDEA and
Eclipse.

Installing Maven
Prerequisites:
Ensure that Java is installed on
the machine. Maven requires Java
to run. The trainees should have
the Java Development Kit (JDK)
installed and the JAVA_HOME
environment variable set.
Steps to Install Maven:
1. Download Maven:
Go to the Maven o\cial
download page.
Download the latest binary
zip archive or tar.gz Mle.
2. Extract the Archive:
Extract the downloaded
archive to a directory of your
choice (e.g., C:\\Program
Files\\Apache\\maven
on Windows or
/usr/local/apache-
maven on macOS/Linux).
3. Set Environment Variables:
Windows:
Right-click on 'This PC'
or 'My Computer', then
go to Properties →
Advanced System

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 3 of 43
:
Settings →
Environment Variables.
Add a new system
variable named
MAVEN_HOME pointing
to the Maven directory.
Append the bin
directory of Maven to
the Path system
variable:
C:\\Program
Files\\Apache\\maven\\bin.
macOS/Linux:
Open
.bash_profile
or .zshrc Mle in
your home directory
and add:
export MAVEN_HOME=/usr/local/apache-maven
export PATH=$MAVEN_HOME/bin:$PATH

Run source
~/.bash_profile
or source
~/.zshrc to apply
the changes.
4. Verify Installation:
Open a terminal or
command prompt and type
mvn -version.
You should see the Maven
version information along
with Java details if Maven is
correctly installed.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 4 of 43
:
Setting up Maven in
IDEs
IntelliJ IDEA:
1. Maven Integration:
IntelliJ IDEA has Maven
integration built-in, so no
additional setup is required.
When creating a new
project, you can select
Maven as the project type,
and IntelliJ will
automatically generate the
pom.xml Mle and manage
the project structure.
2. Importing a Maven Project:
If you already have a Maven
project, you can import it by
opening IntelliJ and
selecting File → Open,
then navigating to the
pom.xml Mle of your
project.
3. Maven Tool Window:
IntelliJ provides a Maven
tool window where you can
run Maven goals, view the
lifecycle, and manage
dependencies directly from
the IDE.
Eclipse:
1. Installing the Maven Plugin:
Eclipse requires the m2e
plugin for Maven integration,
though many versions of
Eclipse come with this

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 5 of 43
:
plugin pre-installed.
To install it manually: Help
→ Eclipse
Marketplace → Search
for "m2e" → Install.
2. Creating a Maven Project:
Go to File → New →
Project → Maven →
Maven Project.
Follow the wizard to set up
your project, specifying
details like GroupId,
ArtifactId, and packaging
type.
3. Importing a Maven Project:
If you have an existing
Maven project, import it by
selecting File → Import
→ Maven → Existing
Maven Projects, then
point to the directory
containing the pom.xml.
4. Maven Integration:
Eclipse provides a "Maven"
perspective that allows you
to run Maven commands,
manage dependencies, and
conMgure the build lifecycle
from within the IDE.

Understanding the .m2


Directory and
settings.xml
The .m2 Directory:
Located in the user's home

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 6 of 43
:
directory (e.g.,
C:\\Users\\YourName\\.m2
on Windows or
/home/YourName/.m2 on
macOS/Linux).
Contains the repository folder
where Maven stores downloaded
dependencies. This is known as
the local repository.
You can delete this folder if you
want to force Maven to re-
download dependencies, but
usually, Maven manages it
automatically.
settings.xml File:
Located in the .m2 directory. This
Mle allows you to customize the
behavior of Maven globally across
all projects.
Common conMgurations include:
Mirror conMguration to
point Maven to a speciMc
repository.
Proxy settings if you're
behind a Mrewall or using a
corporate network.
Local repository location
customization.
Example settings.xml:

<settings>
<mirrors>
<mirror>
<id>central</id>
<mirrorOf>central</mirrorOf>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 7 of 43
:
<url><http://mycompany.com/maven2></url>
</mirror>
</mirrors>
<proxies>
<proxy>
<id>example-proxy</id>
<active>true</active>
<protocol>http</protocol>
<host>proxy.mycompany.com</host>
<port>8080</port>
</proxy>
</proxies>
</settings>

Project Object Model


(POM)
The POM (Project Object Model) is the
core of a Maven project. Understanding
the POM Mle is essential because it
contains all the conMguration details for
a Maven project.

Structure of a
pom.xml File
The pom.xml Mle is an XML Mle
that contains information about the
project and conMguration details
used by Maven to build the project.
Here’s a basic structure of a
pom.xml Mle:

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 8 of 43
:
<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-
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>My App</name>
<url><http://maven.apache.org></url>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 9 of 43
:
</build>
</project>

Key Elements in POM


1. modelVersion::
This speciMes the version of the
POM model being used. Currently,
4.0.0 is the default and most
widely used version.
2. groupId::
The groupId uniquely identiMes
your project across all projects.
Typically, it follows the reverse
domain name convention (e.g.,
com.example).
3. artifactId::
The artifactId is the name of the
jar without the version. It is the
name of the project.
4. version::
The version is the project’s current
version. Maven uses this version
to distinguish between different
versions of the same project.
Versions can be speciMc like
1.0.0, or they can include
SNAPSHOT, which indicates a
version in development.
5. packaging::
The type of artifact this project
produces. Common packaging
types are jar, war, pom, etc.
If omitted, jar is assumed by

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 10 of 43
:
default.
h. name and url::
These are optional elements used
to provide a human-readable
name and project URL.
7. dependencies::
The dependencies section lists
all the external libraries your
project depends on. Maven will
download these libraries
automatically from the central
repository or other speciMed
repositories.
j. build::
The build section is used to
specify how the project should be
built. This includes specifying
plugins, custom build directories,
resources, etc.

Dependencies and
Dependency
Management
Dependencies:
Dependencies are external
libraries that your project needs to
work. You specify these in the
dependencies section of the
POM.
Maven automatically downloads
the speciMed versions of
dependencies and any transitive
dependencies they require.
Example:

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 11 of 43
:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
</dependency>
</dependencies>

Transitive Dependencies:
Maven resolves transitive
dependencies automatically. For
example, if your project depends
on A, and A depends on B, Maven
will include B as a dependency in
your project.

Maven Dependency
Scopes and ProMles
1. Dependency Scopes
Maven provides several scopes for
dependencies, each determining at what
phase of the build process the
dependency is available and whether it
is included in the Mnal artifact (e.g., a
JAR or WAR Mle). Understanding these
scopes is crucial for managing project
dependencies effectively.
Here’s a detailed explanation of each
scope, with examples:

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 12 of 43
:
a. compile Scope
Default Scope
Scope: If no scope is
speciMed, Maven uses compile by
default.
Availability
Availability: The dependency is
available in all phases of the build
lifecycle, including compilation,
testing, and packaging.
Inclusion in Final Artifact
Artifact: The
dependency is included in the Mnal
artifact.
Typical Use
Use: Used for
dependencies required to build,
test, and run the project.
Example:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
<scope>compile</scope> <!-- This is the default scope -->
</dependency>

In this example, commons-lang3


is a utility library used during all
phases of the build, so it’s
speciMed with compile scope.

b. provided Scope
Availability
Availability: The dependency is

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 13 of 43
:
available at compile-time but is not
included in the Mnal artifact.
Inclusion in Final Artifact
Artifact: Not
included in the Mnal artifact. The
assumption is that the runtime
environment (e.g., a web server)
will provide it.
Typical Use
Use: Used for
dependencies that are provided by
the runtime environment, such as
servlet APIs provided by an
application server.
Example:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>

Here, the javax.servlet-api


is only needed for compilation
and testing. It’s expected to be
provided by the server (e.g.,
Tomcat) in production, so it’s
marked with provided scope.

c. runtime Scope
Availability
Availability: The dependency is
not required for compilation but is

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 14 of 43
:
needed during runtime, including
execution and tests.
Inclusion in Final Artifact
Artifact: The
dependency is included in the Mnal
artifact.
Typical Use
Use: Used for
dependencies that are needed only
at runtime, like JDBC drivers.
Example:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
<scope>runtime</scope>
</dependency>

In this example, the MySQL JDBC


driver is not required for compiling
the code but is needed at runtime
when the application connects to
a MySQL database.

d. test Scope
Availability
Availability: The dependency is
available only for the test
compilation and execution phases.
Inclusion in Final Artifact
Artifact: Not
included in the Mnal artifact.
Typical Use
Use: Used for libraries that
are required only for testing, such

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 15 of 43
:
as JUnit or Mockito.
Example:

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>

Here, JUnit is only needed for


running unit tests and isn’t
included in the Mnal build output,
so it’s scoped as test.

e. system Scope
Availability
Availability: The dependency is
available for compilation and
testing but must be explicitly
provided by the developer on the
system.
Inclusion in Final Artifact
Artifact: Not
included in the Mnal artifact.
Typical Use
Use: Used rarely when the
dependency is not available in any
remote repository and must be
provided locally.
Important
Important: You must explicitly
provide the path to the JAR Mle
using the <systemPath>
element.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 16 of 43
:
Example:

<dependency>
<groupId>com.example</groupId>
<artifactId>custom-lib</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/custom-lib.jar</systemPat
</dependency>

In this example, custom-


lib.jar is not available in any
Maven repository and is instead
provided manually in the lib
directory of the project.

Maven ProMles
Maven proMles allow you to customize
the build process for different
environments or situations. A proMle can
modify the default behavior by adding,
removing, or overriding certain parts of
the POM, such as dependencies,
plugins, properties, etc.

How ProMles Work


Activation: ProMles can be activated
explicitly using the P nag in the Maven
command or automatically based on
certain conditions (e.g., OS type, JDK

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 17 of 43
:
version, environment variables).
Scope: ProMles can modify the build
process for a particular environment,
such as development, testing, or
production.

Creating and Using


ProMles
a. Simple ProMle
Example
This proMle will activate different
conMgurations based on whether you’re
in a development or production
environment.
POM with ProMles:

<project>
...
<profiles>
<profile>
<id>development</id>
<properties>
<environment.name>dev</environment.name>
<db.url>jdbc:h2:mem:devdb</db.url>
</properties>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
</profile>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 18 of 43
:
<profile>
<id>production</id>
<properties>
<environment.name>prod</environment.name>
<db.url>jdbc:mysql://prod-server/db</db.url>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
</profile>
</profiles>
</project>

Explanation:
Development ProMle: Activates
a H2 in-memory database for
development. This is useful for
quick setup and teardown without
affecting the production
database.
Production ProMle: Uses a
MySQL database for the
production environment.
Activating a ProMle:
To activate the development
proMle:

mvn clean install -Pdevelopment

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 19 of 43
:
To activate the production
proMle:

mvn clean install -Pproduction

b. ProMle Activation
Based on Conditions
ProMles can also be activated based on
various conditions, such as the
operating system, JDK version, or
environment variables.
POM with Conditional ProMles:

<project>
...
<profiles>
<profile>
<id>windows</id>
<activation>
<os>
<family>Windows</family>
</os>
</activation>
<properties>
<env.name>windows-env</env.name>
</properties>
</profile>

<profile>
<id>jdk-11</id>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 20 of 43
:
<activation>
<jdk>11</jdk>
</activation>
<properties>
<jdk.version>11</jdk.version>
</properties>
</profile>
</profiles>
</project>

Explanation:
Explanation:
Windows
Windows ProMle:
ProMle: Activated
automatically when Maven is run
on a Windows operating system.
JDK
JDK 11
11 ProMle:
ProMle: Activated
automatically when Maven
detects that the project is being
built with JDK 11.
Activating
Activating Automatically:
Automatically:
If Maven is running on a Windows
machine, the windows proMle is
activated automatically.
If Maven is using JDK 11, the
jdk-11 proMle is activated
automatically.

Maven
Maven Build
Build Lifecycle
Lifecycle
The Maven build lifecycle is a sequence
of phases that deMne the order in which
tasks are executed during the build
process of a Maven project. Maven has
three built-in build lifecycles:

1.
1. Default
Default Lifecycle
Lifecycle

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 21 of 43
:
(Build)
(Build)
This is the main lifecycle that handles
project deployment. It consists of 23
phases, the most important of which
are:

validate
validate: Validates the project is
correct and all necessary information is
available.
compile
compile: Compiles the source code of
the project.
test
test: Runs the tests using a suitable
unit testing framework (like JUnit).
package
package: Packages the compiled code
into a distributable format, such as a
JAR or WAR Mle.
verify
verify: Runs any checks to verify the
package is valid and meets quality
criteria.
install
install: Installs the package into the
local repository, for use as a
dependency in other projects locally.
deploy
deploy: Copies the Mnal package to the
remote repository for sharing with other
developers and projects.

2.
2. Clean
Clean Lifecycle
Lifecycle
This lifecycle is used to clean up
artifacts created by the previous build. It
consists of three phases:

pre-clean
pre-clean: Executes processes needed
before the actual project cleaning.
clean
clean: Removes Mles generated during
the previous build.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 22 of 43
:
post-clean
post-clean: Executes processes
needed after the project cleaning.

3.
3. Site
Site Lifecycle
Lifecycle
This lifecycle is used to create the
project's site documentation. It consists
of four phases:

pre-site
pre-site: Executes processes needed
before the actual project site
generation.
site
site: Generates the project's site
documentation.
post-site
post-site: Executes processes needed
after the site generation, preparing for
site deployment.
site-deploy
site-deploy: Deploys the generated
site to a web server.

How
How to
to Use
Use the
the Build
Build
Lifecycle
Lifecycle
You can execute any of the phases
using the Maven command:

mvn <phase>

For example, running mvn install


will run all the phases leading up to and
including the install phase.
Understanding these phases allows you
to control the build process and ensure
that your project is built, tested,
packaged, and deployed correctly.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 23 of 43
:
Key
Key Commands
Commands for for
the
the Default
Default Lifecycle
Lifecycle
When you run a Maven command, such
as mvn package, Maven executes all
the phases up to and including the
package phase:

mvn validate: Validates the project.


mvn compile: Compiles the source
code of the project.
mvn test: Runs the tests using a
suitable unit testing framework.
mvn package: Takes the compiled
code and packages it into a JAR, WAR,
etc.
mvn install: Installs the package
into the local repository, making it
available for other projects locally.
mvn deploy: Copies the Mnal package
to the remote repository.

Phases
Phases of
of the
the Clean
Clean
Lifecycle
Lifecycle
pre-clean: Executes processes
needed prior to cleaning.
clean: Removes Mles generated during
the previous build.
post-clean: Executes processes
needed after cleaning.

When you run mvn clean, Maven


executes all phases of the Clean
lifecycle.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 24 of 43
:
Phases
Phases of
of the
the Site
Site
Lifecycle
Lifecycle
pre-site: Executes processes
needed prior to generating the site
documentation.
site: Generates the project’s site
documentation.
post-site: Executes processes
needed after generating the site
documentation.
site-deploy: Deploys the generated
site documentation to the server.

When you run mvn site, Maven


executes all phases of the Site lifecycle
to generate the project documentation.

Maven
Maven Repositories
Repositories
Maven repositories are a central part of
the Maven build system. They are where
Maven stores and retrieves project
dependencies, plugins, and other
artifacts. Understanding how
repositories work and how to manage
them is crucial for effectively using
Maven.

Types
Types of
of Maven
Maven
Repositories
Repositories
Maven supports three types of
repositories:

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 25 of 43
:
1. Local
Local Repository:
Repository:
The local repository is a
directory on your computer
where Maven stores
downloaded dependencies,
plugins, and other artifacts.
When you build a Maven
project, Maven Mrst checks the
local repository to see if the
required dependencies are
already available. If they are,
Maven uses them; if not,
Maven downloads them from
a remote repository (such as
the central repository) and
stores them locally.
The default location of the
local repository is
~/.m2/repository (on
Unix-based systems) or
C:\\Users\\YourUsername\\.m2\\repository
(on Windows).
You can conMgure the location
of the local repository in the
settings.xml Mle:

<settings>
<localRepository>C:/path/to/your/local/repo</localRepos
</settings>

2. Central
Central Repository:
Repository:
The central repository is a global,

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 26 of 43
:
publicly available repository
hosted by the Maven project. It
contains a vast collection of open-
source libraries, plugins, and other
project artifacts.
The central repository is the
default source from which Maven
downloads dependencies if they
are not found in the local
repository.
Maven automatically connects to
the central repository when you
request a dependency that is not
available locally.
3. Remote
Remote Repository:
Repository:
A remote repository is any
repository that is hosted on a
web server other than the
central repository.
Organizations often maintain
their own remote repositories
to store proprietary artifacts,
plugins, or third-party libraries
that are not available in the
central repository.
You can conMgure Maven to
use a remote repository by
adding it to your pom.xml or
settings.xml Mle.
Example in pom.xml:

<repositories>
<repository>
<id>my-company-repo</id>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 27 of 43
:
<url><http://repository.mycompany.com/maven2></url>
</repository>
</repositories>

How
How Maven
Maven Resolves
Resolves
Dependencies
Dependencies
Maven follows a speciMc order to
resolve dependencies:

1. Local
Local Repository:
Repository: Maven checks the
local repository Mrst. If the dependency
is found, Maven uses it.
2. Remote
Remote Repositories:
Repositories: If the
dependency is not found in the local
repository, Maven checks any
conMgured remote repositories.
3. Central
Central Repository:
Repository: If the dependency
is not found in any remote repositories,
Maven checks the central repository.
4. Fail:
Fail: If Maven cannot Mnd the
dependency in any repository, the build
fails with an error.

Managing
Managing
Dependencies
Dependencies with
with
Repositories
Repositories
Adding
Adding Dependencies
Dependencies
You add dependencies to your
project by specifying them in the
dependencies section of the
pom.xml Mle. Maven then resolves
these dependencies by checking

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 28 of 43
:
the repositories in the order
described above.
Example:
xmlCopy code
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
</dependency>
</dependencies>

Excluding
Excluding Transitive
Transitive
Dependencies
Dependencies
Sometimes, a dependency might
bring in transitive dependencies
that you don’t want. You can
exclude these unwanted transitive
dependencies using the
<exclusions> tag.
Example:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifact
</exclusion>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 29 of 43
:
</exclusions>
</dependency>
</dependencies>

Using
Using Repository
Repository
Managers
Managers
Organizations often use repository
managers like Nexus or Artifactory to:

Cache
Cache Artifacts:
Artifacts: Repository
managers cache dependencies from
remote repositories, reducing download
times and providing redundancy in case
a remote repository becomes
unavailable.
Store
Store Internal
Internal Artifacts:
Artifacts:
Organizations can store their internal or
proprietary libraries and plugins in a
secure location.
Enforce
Enforce Policies:
Policies: Repository
managers can enforce security policies,
licensing, and artifact versioning rules.

Example
Example of
of ConMguring
ConMguring aa Nexus
Nexus
Repository:
Repository:

<repositories>
<repository>
<id>nexus-repo</id>
<url><http://nexus.mycompany.com/repository/maven-public/></
</repository>
</repositories>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 30 of 43
:
Using
Using Mirrors
Mirrors to
to
Redirect
Redirect Repositories
Repositories
Mirrors allow you to redirect Maven to
use a different repository for a given
URL pattern. This is useful for routing all
requests that would go to the central
repository to an internal mirror.
Example in settings.xml:

<mirrors>
<mirror>
<id>central-mirror</id>
<mirrorOf>central</mirrorOf>
<url><http://mycompany.com/maven/central></url>
</mirror>
</mirrors>

In this example, all requests to the


central repository are redirected to
http://mycompany.com/maven/central.

Maven
Maven Dependency
Dependency
Management
Management
Maven's dependency management
system is one of its most powerful
features. It automatically handles the
inclusion of libraries that your project
needs, as well as their transitive
dependencies (dependencies of your

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 31 of 43
:
dependencies). Understanding how to
manage these dependencies effectively
is key to maintaining a clean and
e\cient build.

Dependency
Dependency Scopes
Scopes
(Recap)
(Recap)
As we covered earlier, Maven supports
different dependency scopes (compile,
provided, runtime, test, system).
These scopes determine when a
dependency is available during the build
process and whether it is included in the
Mnal artifact.
Here's a quick recap:

compile
compile: Available in all phases and
included in the Mnal artifact.
provided
provided: Available at compile-time but
not included in the Mnal artifact (e.g.,
servlet APIs provided by the server).
runtime
runtime: Not needed for compilation
but required during execution (e.g.,
JDBC drivers).
test
test: Available only for testing, not
included in the Mnal artifact.
system: Similar to provided, but the
system
JAR must be available on the local
system.

Transitive
Transitive
Dependencies
Dependencies
Transitive dependencies are

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 32 of 43
:
dependencies that are required by the
libraries your project depends on. Maven
resolves these automatically, so you
don’t have to manually include every
single dependency in your pom.xml.
Example
Example of
of Transitive
Transitive
Dependencies:
Dependencies:

Suppose your project depends on


spring-core, which in turn depends
on commons-logging.
Maven will automatically download
commons-logging as a transitive
dependency when you add spring-
core to your project.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.9</version>
</dependency>

Explanation
Explanation: When Maven processes
this dependency, it will also download
and include any libraries that spring-
core depends on, such as commons-
logging.

Dependency
Dependency
Management
Management inin Multi-
Multi-
Module
Module Projects
Projects
In multi-module projects, you often have

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 33 of 43
:
a parent POM that deMnes
dependencies for all modules. Maven
provides a
<dependencyManagement> section
that allows you to centrally manage
dependency versions across multiple
modules.
Using <dependencyManagement> in
Using in
the
the Parent
Parent POM:
POM:

<project>
<groupId>com.example</groupId>
<artifactId>parent-project</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
</dependencies>
</dependencyManagement>

<modules>
<module>module-a</module>
<module>module-b</module>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 34 of 43
:
</modules>
</project>

Explanation
Explanation: Dependencies
deMned in
<dependencyManagement> are
not automatically included in the
child modules. Instead, they
provide a version and scope
template that child modules can
use.
Child
Child Module
Module POM:
POM:

<project>
<parent>
<groupId>com.example</groupId>
<artifactId>parent-project</artifactId>
<version>1.0.0</version>
</parent>

<artifactId>module-a</artifactId>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
</dependencies>
</project>

Explanation
Explanation: The child module

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 35 of 43
:
inherits the version and scope of
spring-core from the parent
POM, thanks to the
<dependencyManagement>
section.

Excluding
Excluding Unwanted
Unwanted
Transitive
Transitive
Dependencies
Dependencies
Sometimes, you might want to exclude a
transitive dependency that is brought in
by one of your dependencies but is not
needed by your project.
Example
Example of
of Excluding
Excluding Transitive
Transitive
Dependencies:
Dependencies:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.4</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>

Explanation
Explanation: This conMguration
excludes the spring-boot-
starter-tomcat dependency, which
might be useful if you’re using a

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 36 of 43
:
different server (e.g., Jetty) and don’t
want Tomcat libraries included.

Managing
Managing Connicts
Connicts
with
with Dependency
Dependency
Mediation
Mediation
When multiple versions of the same
dependency are included via transitive
dependencies, Maven uses a process
called "dependency mediation" to
determine which version to use. Maven
usually selects the nearest deMnition
(i.e., the version speciMed in the
pom.xml or the version closest to the
root of the dependency tree).
Example
Example of
of Dependency
Dependency Connict:
Connict:

If A depends on B:1.0 and C depends


on B:2.0, and both A and C are
included in your project, Maven will
choose one version of B.
You can control which version is
selected by explicitly declaring the
desired version in your pom.xml.

<dependency>
<groupId>com.example</groupId>
<artifactId>B</artifactId>
<version>2.0</version>
</dependency>

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 37 of 43
:
Explanation
Explanation: By explicitly declaring the
version of B, you override the transitive
versions and ensure that B:2.0 is
used.

Best
Best Practices
Practices for
for
Dependency
Dependency
Management
Management
1. Minimize
Minimize the
the Number
Number of
of
Dependencies
Dependencies: Only include the
libraries that are essential to your
project. More dependencies can lead to
larger builds and more complex
dependency graphs, increasing the risk
of connicts.
Use <dependencyManagement>: In
2. Use
multi-module projects, use the
<dependencyManagement> section
to centralize the management of
dependency versions.
3. Exclude
Exclude Unnecessary
Unnecessary Transitive
Transitive
Dependencies
Dependencies: Use the
<exclusions> tag to remove
dependencies that are not needed by
your project.
4. Resolve
Resolve Connicts
Connicts Explicitly
Explicitly: When
facing version connicts, explicitly
declare the version you want to use in
your pom.xml.
5. Regularly
Regularly Update
Update Dependencies
Dependencies:
Keep your dependencies up to date to
beneMt from the latest features and
security patches.

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 38 of 43
:
Trending
Trending Blogs
Blogs

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 39 of 43
:
Maven Tutorial
Tutorial Servlet
Servlet Short Note
Maven is a build automation tool Servlet Short Note
primarily used for Java projects. It
addresses two main aspects of
building software: dependency Read
Read Blogs
Blogs
management and project build
Premium
Premium Courses
Courses
lifecycle management.

Read
Read Blogs
Blogs

Premium
Premium Courses
Courses

Help Others, Please Share

Share
Share on
on Facebook
Facebook

Share
Share on
on WhatsApp
WhatsApp

Share
Share on
on LinkedIn
LinkedIn

Share
Share on
on Twitter
Twitter

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 40 of 43
:
https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 41 of 43
:
Learn
Learn Code
Code With
With Durgesh
Durgesh
Learn Code With Durgesh offers wide variety
of free and Premium courses on YouTube
channel and website. We are serving lakhs of
students and professionals.

!! Happy Coding !!
Products
Products
Master Spring Boot With Project Course

React Js Ecommerce Project Course

React + Spring Boot Full Stack

Free Courses

Contact
Contact
Substring Technologies, Vijayeepur ,
Vishesh Khand 2 Gomti Nagar, Lucknow, INDIA,
226010

[email protected]

+91-9839466732

Get
Get In
In Touch
Touch
YouTube

Facebook

Instagram

Linkedin

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 42 of 43
:
Copyright © 2023: Substring
Substring Technologies
Technologies Pvt
Pvt Ltd.
Ltd.
All Rights Reserved.

Refund
Refund Policy
Policy
Privacy
Privacy Policy
Policy
Terms
Terms of
of Service
Service

https://www.learncodewithdurgesh.com/blogs/maven-tutorial 21/10/24, 8 45 AM
Page 43 of 43
:

You might also like