Maven how to add dependency

Maven how to add dependency

Maven how to add dependency

Introduction to the Dependency Mechanism

Dependency management is a core feature of Maven. Managing dependencies for a single project is easy. 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.

Learn more about:

Transitive Dependencies

Maven avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically.

This feature is facilitated 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.

With transitive dependencies, the graph of included libraries can quickly grow quite large. For this reason, there are additional features that limit which dependencies are included:

Although transitive dependencies can implicitly include desired dependencies, it is a good practice to explicitly specify the dependencies your source code uses directly. This best practice proves its value especially when the dependencies of your project change their dependencies.

For example, assume that your project A specifies a dependency on another project B, and project B specifies a dependency on project C. If you are directly using components in project C, and you don’t specify project C in your project A, it may cause build failure when project B suddenly updates/removes its dependency on project C.

Another reason to directly specify dependencies is that it provides better documentation for your project: one can learn more information by just reading the POM file in your project, or by executing mvn dependency:tree.

Maven also provides dependency:analyze plugin goal for analyzing the dependencies: it helps making this best practice more achievable.

Dependency Scope

Dependency scope is used to limit the transitivity of a dependency and to determine when a dependency is included in a classpath.

There are 6 scopes:

Each of the scopes (except for import ) affects transitive dependencies in different ways, as is demonstrated in the table below. If a dependency is set to the scope in the left column, a transitive dependency of that dependency with the scope across the top row results in a dependency in the main project with the scope listed at the intersection. If no scope is listed, it means the dependency is omitted.

compileprovidedruntimetest
compilecompile(*)runtime
providedprovidedprovided
runtimeruntimeruntime
testtesttest

(*) Note: it is intended that this should be runtime scope instead, so that all compile dependencies must be explicitly listed. However, if a library you depend on extends a class from another library, both must be available at compile time. For this reason, compile time dependencies remain as compile scope even when they are transitive.

Dependency Management

The dependency management section is a mechanism for centralizing dependency information. When you have a set of projects that inherit from a common parent, it’s possible to put all information about the dependency in the common POM and have simpler references to the artifacts in the child POMs. The mechanism is best illustrated through some examples. Given these two POMs which extend the same parent:

These two example POMs share a common dependency and each has one non-trivial dependency. This information can be put in the parent POM like this:

Then the two child POMs become much simpler:

A second, and very important use of the dependency management section is to control the versions of artifacts used in transitive dependencies. As an example consider these projects:

When maven is run on project B, version 1.0 of artifacts a, b, c, and d will be used regardless of the version specified in their POM.

The reference information about the dependency management tags is available from the project descriptor reference.

Importing Dependencies

The examples in the previous section describe how to specify managed dependencies through inheritance. However, in larger projects it may be impossible to accomplish this since a project can only inherit from a single parent. To accommodate this, projects can import managed dependencies from other projects. This is accomplished by declaring a POM artifact as a dependency with a scope of «import».

Assuming A is the POM defined in the preceding example, the end result would be the same. All of A’s managed dependencies would be incorporated into B except for d since it is defined in this POM.

In the example above Z imports the managed dependencies from both X and Y. However, both X and Y contain dependency a. Here, version 1.1 of a would be used since X is declared first and a is not declared in Z’s dependencyManagement.

This process is recursive. For example, if X imports another POM, Q, when Z is processed it will simply appear that all of Q’s managed dependencies are defined in X.

Bill of Materials (BOM) POMs

Imports are most effective when used for defining a «library» of related artifacts that are generally part of a multiproject build. It is fairly common for one project to use one or more artifacts from these libraries. However, it has sometimes been difficult to keep the versions in the project using the artifacts in synch with the versions distributed in the library. The pattern below illustrates how a «bill of materials» (BOM) can be created for use by other projects.

The root of the project is the BOM POM. It defines the versions of all the artifacts that will be created in the library. Other projects that wish to use the library should import this POM into the dependencyManagement section of their POM.

The parent subproject has the BOM POM as its parent. It is a normal multiproject pom.

Next are the actual project POMs.

The project that follows shows how the library can now be used in another project without having to specify the dependent project’s versions.

Finally, when creating projects that import dependencies, beware of the following:

System Dependencies

Important note: This is deprecated.

Dependencies with the scope system are always available and are not looked up in repository. They are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK, but were available as separate downloads earlier. Typical examples are the JDBC standard extensions or the Java Authentication and Authorization Service (JAAS).

Maven how to add dependency

Introduction to the Dependency Mechanism

Dependency management is a core feature of Maven. Managing dependencies for a single project is easy. 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.

Learn more about:

Transitive Dependencies

Maven avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically.

This feature is facilitated 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.

With transitive dependencies, the graph of included libraries can quickly grow quite large. For this reason, there are additional features that limit which dependencies are included:

Although transitive dependencies can implicitly include desired dependencies, it is a good practice to explicitly specify the dependencies your source code uses directly. This best practice proves its value especially when the dependencies of your project change their dependencies.

For example, assume that your project A specifies a dependency on another project B, and project B specifies a dependency on project C. If you are directly using components in project C, and you don’t specify project C in your project A, it may cause build failure when project B suddenly updates/removes its dependency on project C.

Another reason to directly specify dependencies is that it provides better documentation for your project: one can learn more information by just reading the POM file in your project, or by executing mvn dependency:tree.

Maven also provides dependency:analyze plugin goal for analyzing the dependencies: it helps making this best practice more achievable.

Dependency Scope

Dependency scope is used to limit the transitivity of a dependency and to determine when a dependency is included in a classpath.

There are 6 scopes:

Each of the scopes (except for import ) affects transitive dependencies in different ways, as is demonstrated in the table below. If a dependency is set to the scope in the left column, a transitive dependency of that dependency with the scope across the top row results in a dependency in the main project with the scope listed at the intersection. If no scope is listed, it means the dependency is omitted.

compileprovidedruntimetest
compilecompile(*)runtime
providedprovidedprovided
runtimeruntimeruntime
testtesttest

(*) Note: it is intended that this should be runtime scope instead, so that all compile dependencies must be explicitly listed. However, if a library you depend on extends a class from another library, both must be available at compile time. For this reason, compile time dependencies remain as compile scope even when they are transitive.

Dependency Management

The dependency management section is a mechanism for centralizing dependency information. When you have a set of projects that inherit from a common parent, it’s possible to put all information about the dependency in the common POM and have simpler references to the artifacts in the child POMs. The mechanism is best illustrated through some examples. Given these two POMs which extend the same parent:

These two example POMs share a common dependency and each has one non-trivial dependency. This information can be put in the parent POM like this:

Then the two child POMs become much simpler:

A second, and very important use of the dependency management section is to control the versions of artifacts used in transitive dependencies. As an example consider these projects:

When maven is run on project B, version 1.0 of artifacts a, b, c, and d will be used regardless of the version specified in their POM.

The reference information about the dependency management tags is available from the project descriptor reference.

Importing Dependencies

The examples in the previous section describe how to specify managed dependencies through inheritance. However, in larger projects it may be impossible to accomplish this since a project can only inherit from a single parent. To accommodate this, projects can import managed dependencies from other projects. This is accomplished by declaring a POM artifact as a dependency with a scope of «import».

Assuming A is the POM defined in the preceding example, the end result would be the same. All of A’s managed dependencies would be incorporated into B except for d since it is defined in this POM.

In the example above Z imports the managed dependencies from both X and Y. However, both X and Y contain dependency a. Here, version 1.1 of a would be used since X is declared first and a is not declared in Z’s dependencyManagement.

This process is recursive. For example, if X imports another POM, Q, when Z is processed it will simply appear that all of Q’s managed dependencies are defined in X.

Bill of Materials (BOM) POMs

Imports are most effective when used for defining a «library» of related artifacts that are generally part of a multiproject build. It is fairly common for one project to use one or more artifacts from these libraries. However, it has sometimes been difficult to keep the versions in the project using the artifacts in synch with the versions distributed in the library. The pattern below illustrates how a «bill of materials» (BOM) can be created for use by other projects.

The root of the project is the BOM POM. It defines the versions of all the artifacts that will be created in the library. Other projects that wish to use the library should import this POM into the dependencyManagement section of their POM.

The parent subproject has the BOM POM as its parent. It is a normal multiproject pom.

Next are the actual project POMs.

The project that follows shows how the library can now be used in another project without having to specify the dependent project’s versions.

Finally, when creating projects that import dependencies, beware of the following:

System Dependencies

Important note: This is deprecated.

Dependencies with the scope system are always available and are not looked up in repository. They are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK, but were available as separate downloads earlier. Typical examples are the JDBC standard extensions or the Java Authentication and Authorization Service (JAAS).

How to add dependencies to a Maven project

Used software

This tutorial considers the following software and environment:

Editing your pom.xml file

In this tutorial we will be adding Apache Commons Email library as a dependency to our Maven project. Start by opening your pom.xml file and add the Commons email dependency to the project. The groupId, artifactId and version to be used in the dependency element can be easily found in the online Maven global repository or in the official webpage of the dependency provider, ie Apache dependencies info is usually available at the Apache website, Spring dependencies info is usually available at the Spring website, etc.

After editing your pom.xml and adding the Commons Email dependency, the xml file should look like the following:

Using the Commons Email dependency

Now that we added the Commons Email dependency to our project we can start using it in our classes:

After defining the class you can issue the Maven build command. Note that the Commons Email library will be downloaded and added as a dependency to your project during the build process. Issue the following command in your project root directory:

Updating the dependency references in Eclipse

If you are using Eclipse as your IDE you must refresh the project classpath so it knows about the dependencies you just added. To acomplish this you just need to issue the following Maven command after the build process finishes:

Now the Commons Email jars are included in your project classpath:

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

Download source code from this article

Related Articles

Comments

Gonçalo Marques is a Software Engineer with several years of experience in software development and architecture definition. During this period his main focus was delivering software solutions in banking, telecommunications and governmental areas. He created the Bytes Lounge website with one ultimate goal: share his knowledge with the software development community. His main area of expertise is Java and open source.

He is also the author of the WiFi File Browser Android application:

Maven how to add dependency

Usage

Brief examples on how to use the dependency goals:

dependency:copy

The artifact version is optional. If not set, the plugin will attempt to resolve it from the project dependencies and then the dependencyManagement section.

See the Overwrite Rules section for rules about how overwriting is handled.

Configure the plugin something like this if you intend to bind it to execute along with your build:

If you intend to configure this goal for execution on the command line using:

you must not put the configuration inside the executions tag. Your configuration should look like this:

dependency:copy-dependencies

The artifacts can be placed in subfolders based on type. For example:

The artifacts can be placed in a subfolder per artifact. For example: \outputDirectory\junit-junit-3.8.1
This feature also works with the subfolders per type. For example: \outputDirectory\jars\junit-junit-3.8.1\

Also included is the ability to include or exclude by type (war, jar etc), scope (runtime, test, etc), classifier (jdk14, sources, etc), groupId, artifactId, or a combination of them.

Note: As of 2.0-alpha-5, you may mix includes and excludes of the same category (ie scope). Includes are processed before excludes.

See the Overwrite Rules section for rules about how overwriting is handled.

The goal can also be launched from the command line like: mvn dependency:copy-dependencies [optional params]

dependency:unpack

This goal is meant to be bound to a lifecycle and configured in your pom.xml. It will resolve the artifact from the repository and place a copy in the specified location. Multiple artifacts can be defined in a single execution. A default outputDirectory is specified but can be overridden for each ArtifactItem by setting the optional outputDirectory field.

A single artifact can be unpacked multiple times if different include/exclude parameters are defined for each artifactItem

See the Overwrite Rules section for rules about how overwriting is handled.

The artifact version is optional. If not set, the plugin will attempt to resolve it from the project dependencies and then the dependencyManagement section.

Configure the plugin something like this if you intend to bind it to execute along with your build:

If you intend to configure this goal for execution on the command line using:

you must not put the configuration inside the executions tag. Your configuration should look like this:

dependency:unpack-dependencies

This goal can be bound to a lifecycle and configured in your pom.xml. It will resolve the dependencies (including transitive dependencies) from the repository and unpack them to the specified location.

Unpack-dependencies includes transitive dependencies by default. To include only direct dependencies, set the excludeTransitive parameter to true.

Dependencies can be included or excluded by a list of types. See unpack-dependencies for details.

The artifacts can be unpacked in subfolders based on type. For example:

The artifacts can be placed in a subfolder per artifact. For example: \outputDirectory\junit-junit-3.8.1
This feature also works with the subfolders per type. For example: \outputDirectory\jars\junit-junit-3.8.1\

Filters can be applied to include or exclude certain file or filesets as necessary

Also included is the ability to include or exclude by type (war, jar etc), scope (runtime, test, etc), classifier (jdk14, sources, etc), groupId, artifactId, or a combination of them.

Note: As of 2.0-alpha-5, you may mix includes and excludes of the same category (ie scope). Includes are processed before excludes.

See the Overwrite Rules section for rules about how overwriting is handled.

The goal can also be launched from the command line like: mvn dependency:unpack-dependencies [optional params]

Overwrite Rules

Artifacts are copied or unpacked using the following rules:

dependency:resolve

This goal simply tells maven to resolve all test scope (includes compile) dependencies and then displays the resolved versions. This is intended to help ensure all dependencies are downloaded to the local repository. This is useful when troubleshooting or during intermittent remote repository failures when repeatedly building multiproject modules is undersirable and the build is failing on dependency resolution. It can also be used to quickly determine how versions are being resolved.

dependency:sources

This is the same as the resolve goal except it includes the source attachments if they exist. This is useful when you want to download source attachments to your local repository.

You can also define the markersDirectory either in the pom or settings to be a common location for all projects. This allows the system to resolve sources faster for dependencies that don’t have the sources published. The plugin will store a marker file to describe if the sources were resolved or not. By placing them in a common location, multiple attempts to resolve non-existent sources will be avoided.

dependency:resolve-plugins

This is the same as the resolve goal except it resolves plugins and optionally their dependencies.

dependency:go-offline

dependency:purge-local-repository

In its simplest form, the goal can be called like this:

To add the restriction that the org.apache.maven:maven-plugin-api artifact not be deleted, we can modify the command to this:

Another handy aspect of this goal is the ability to wipe out artifacts at varying depths. These depths are:

To prune dependency artifacts back to their associated artifactId directories (in order to verify proper artifact resolution, for example), simply use this command:

Finally, it’s possible to bind this goal to the build lifecycle. One reason for this might be to clean out all dependencies when the build is initialized, to verify correct resolution.

dependency:analyze

This goal performs byte code analysis to determine missing or unused dependencies. This goal is meant to be launched from the command line. It will fork the build and execute test-compile so there are class files to analyze. If you want to bind analyze in your pom, use the dependency:analyze-only instead.

This goal can be executed from the command line:

dependency:analyze-dep-mgt

This goal looks at the dependencies after final resolution and looks for mismatches in your dependencyManagement section. In versions of maven prior to 2.0.6, it was possible to inherit versions that didn’t match your dependencyManagement. See MNG-1577 for more info.

If this goal detects issues, you should attempt to resolve the discrepancies before upgrading to 2.0.6 to avoid any surprises. This can be done by upgrading or downgrading the version in dependencyManagement to match what is actually being included at runtime, or you can specify a dependency in your project to override what is being included. You can check the results by rerunning this goal. If you decide to override by using a dependency, be sure to note it so you can remove it later after upgrading to 2.0.6. You could also use the dependency:analyze goal to uncover this unused direct dependency.

This goal is also useful for just detecting projects that override the dependencyManagement directly. Set ignoreDirect to false to detect these otherwise normal conditions.

This goal can be executed from the command line:

dependency:analyze-report

dependency:tree

This goal is used to view the dependency hierarchy of the project currently being built. It will output the resolved tree of dependencies that the Maven build process actually uses.

This goal can be executed from the command line:

Optionally, the output parameter can be specified to divert the output to a file:

Also, the outputType parameter can be used to generate different formats of output. The following formats are currently supported:

dependency:build-classpath

This goal will output a classpath string of dependencies from the local repository to a file or log and optionally attach and deploy the file. For instance, the file would contain a classpath string like this:

The resulting file could then be used like this:

In its simplest form, to output the classpath to the log, the goal can be called like this:

or to write the classpath to cp.txt.:

The goal can also be bound to a lifecycle phase with the following configuration:

dependency:list-repositories

This goal is used to list all the repositories that this build depends upon. It will show repositories defined in your settings, poms and declared in transitive dependency poms.

dependency:get

This goal is used to fetch an artifact and (optionally) its dependencies from remote repositories using its Maven coordinates.

How do I add a Maven dependency in Eclipse?

I don’t know how to use Maven at all. I’ve been developing for a couple years with Eclipse and haven’t yet needed to know about it. However, now I’m looking at some docs that suggest I do the following:

«To include it within your project, just add this maven dependency to your build.»

How do I do this with my Eclipse project?

Please assume I know nothing about Maven. I just figured out it might be installed on my computer by typing mvn on the command line, but that’s seriously the extent of my knowledge. I would be happy to continue knowing nothing about Maven if there is an equivalent, non-Maven way of following these instructions with Eclipse.

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

6 Answers 6

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

In fact when you open the pom.xml, you should see 5 tabs in the bottom. Click the pom.xml, and you can type whatever dependencies you want.

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

Maven how to add dependency. Смотреть фото Maven how to add dependency. Смотреть картинку Maven how to add dependency. Картинка про Maven how to add dependency. Фото Maven how to add dependency

You need to be using a Maven plugin for Eclipse in order to do this properly. The m2e plugin is built into the latest version of Eclipse, and does a decent if not perfect job of integrating Maven into the IDE. You will want to create your project as a ‘Maven Project’. Alternatively you can import an existing Maven POM into your workspace to automatically create projects. Once you have your Maven project in the IDE, simply open up the POM and add your dependency to it.

Now, if you do not have a Maven plugin for Eclipse, you will need to get the jar(s) for the dependency in question and manually add them as classpath references to your project. This could get unpleasant as you will need not just the top level JAR, but all its dependencies as well.

Basically, I recommend you get a decent Maven plugin for Eclipse and let it handle the dependency management for you.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *