Dependency Management
This lesson explains how the dependencyManagement element works in Maven.
When working at enterprise-scale, it is common to encounter several dozen projects using a particular version of a dependency. Because of how the projects are intertwined, upgrading or downgrading the version of the dependency in one project may require duplicating the effort across all the projects. This creates a maintenance nuisance where every project’s POM file has to be updated. There could also be other reasons to synchronize the version of a dependency across projects in an enterprise. For instance, because of licensing restrictions or known security vulnerabilities, only “blessed” versions of a dependency are allowed for use in an enterprise. One way to tackle this issue is to use dependency management in Maven. Usually, the set-up consists of a parent POM that is shared among the projects. Within the parent POM we define a section, <dependencyManagement>
, which lists dependencies and their preferred versions. Any child project that inherits from the parent POM can now declare a dependency without the version, as long as the dependency appears in the list of dependencies under the <dependencyManagement>
section in the parent POM.
Another purpose served by the dependency management section is to control the versions of artifacts to be used when they are encountered in transitive dependencies or in dependencies where no version has been specified. The desired versions for transitive dependencies can be specified by project authors in the <dependencyManagement>
section.
Consider the setup of two projects, where the first one acts as a parent and the second as the child. The parent defines a dependency management section as follows:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
</dependencies>
</dependencyManagement>
And the child POM declares a dependency on the Gson artifact as follows:
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
</dependencies>
Note that the version is missing in the child POM and Maven walks up the parent-child hierarchy until it finds a project with a <dependencyManagement>
element and uses the version specified in the <dependencyManagement>
section for the dependency. However, if the child project did define a version, it would override the version listed in the parent POM’s dependency management section. In other words, the <dependencyManagement>
version is used only when the child does not declare a version directly.
The exercises in the widget below span over two example projects. In the first instance the setup is as follows:
Get hands-on with 1400+ tech skills courses.