A guide to excluding dependencies with maven

A guide to excluding dependencies with maven

Maven facilitates the inclusion of transitive dependencies, implying that if module A has a dependency on module B, and module B has a dependency on module C, then module C will automatically become part of the dependency tree for module A. However, scenarios may arise where this automatic inclusion is not desired. For example, in a situation where module A relies on module B, which in turn depends on module C, but module A specifically needs to utilize modules in B that rely on module D.

To address such cases, Maven provides a mechanism called exclusions. Exclusions allow developers to explicitly specify which transitive dependencies should be excluded from the project's dependency resolution.

Let's consider a practical example using the Spring Framework. Assume you are working on a project using Spring, and you wish to exclude a particular version of the Jackson library that Spring transitively depends on. This exclusion is necessary because you intend to use a different version of the Jackson library.

Here's how you can use exclusions in your Maven project:

<dependencies>
    <!-- Dependency on Spring Framework -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.10.RELEASE</version>
        <!-- Exclude the default Jackson dependency that comes with Spring -->
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <!-- Explicitly declare the desired version of Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.5</version> <!-- Specify the version you prefer -->
    </dependency>
</dependencies>

Within the <exclusions> tag, you can include a list of exclusions, each specifying the groupId and artifactId of the transitive dependency you want to exclude. Additionally, the wildcard (*) can be used to indicate the exclusion of all artifacts from a specific groupId. For instance:

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.10.RELEASE</version>
        <!-- Exclude all artifacts from com.fasterxml.jackson.core -->
        <exclusions>
            <exclusion>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>*</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

In this manner, exclusions provide a flexible mechanism for managing dependencies in Maven projects, allowing developers to precisely control the inclusion or exclusion of transitive dependencies based on project requirements.