0

Say we have the following dependency hierarchy in maven:

 +- projectA
 |  +- projectB
 |  |  +- projectC
 |  |  +- projectD

Here projectB needs certain libraries from projectA (let's say libX). But, those libraries are not needed any further in the hierarchy (ie. C and D don't need libX). Now, as projectC and projectE are inheriting all the dependencies from their parent project (projectA), so they can provide for such dependency.

Q. Can we restrict the dependency inheritance at the level of projectB itself, so that we need not exclude it manually everywhere (viz. projectC, projectD, etc.)

Satyendra
  • 1,635
  • 3
  • 19
  • 33
  • If projectA is a project which contains code or even a dependency than is something wrong. Parent are only packaging type `pom` and never contain code. If in that pom a dependency is defined that's simply wrong...General rule never define dependencies in a parent.... – khmarbaise Aug 31 '21 at 09:53

2 Answers2

1

You can try using optional dependencies in projectB, this is the exact use-case :

https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html

In your pom something like :

    <project>
      ...
      <dependencies>
        <!-- declare the dependency to be set as optional -->
        <dependency>
          <groupId>sample.ProjectA</groupId>
          <artifactId>ProjectA</artifactId>
          <version>1.0</version>
          <scope>compile</scope>
          <optional>true</optional> <!-- value will be true or false only -->
        </dependency>
      </dependencies>
    </project>
Cédric Couralet
  • 4,913
  • 1
  • 21
  • 21
1

You can set <optional>true</optional> on the dependency in B.

Please note that if C calls a method of B that needs libX, this will then fail.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142