How to replace a transitive dependency library in a maven project

Viewed 322

I have a dependency library which is being pulled in by a library which I have included in my POM. This transitive dependency has been flagged as an operational risk by a security scan and asked to upgrade it to the latest version. I need to understand how that can be done? I tried excluding the library from the POM and then declare a direct dependency on the latest version of the same transitive dependency but I get classNotFound exception.

Code elaboration:- Direct dependency -> hibernate-core Transitive dependency which as been flagged -> ANTLR 2.7.7

The failed fix that I have tried ->

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.18.Final</version>
        <exclusions>
            <exclusion>
                <groupId>antlr</groupId>
                <artifactId>antlr</artifactId>
            </exclusion>
        </exclusions> 
    </dependency>
    <dependency>
        <groupId>antlr</groupId>
        <artifactId>antlr</artifactId>
        <version>3.0ea8</version>
    </dependency>

Please suggest a generic approach to replacing a transitive library.

1 Answers

There is no need for exclusions. You can override transitive dependencies in the <dependencyManagement> like:

<dependencyManagement>
  <dependencies>
     <dependency>
       <groupId>antlr</groupId>
       <artifactId>antlr</artifactId>
       <version>3.0ea8</version>
    </dependency>
...

This will override all transitive occurrences of the library with the version you specify.

But this does not protect you from classNotFound exceptions. If you update a library, class names may have changed and your program might break.

Related