If two dependences of a module both have a common depdnendency but have different versions specified in their poms, which version is used when building the module?
For example
Artifact-A
/ \
/ \
/ \
Artifact-B Artifact-C
\ /
1.6.0 \ / 1.8.0
\ /
Artifact-D
Similarly in the scenario detailed below what version of Artifact-C would Artifact-A use?
Artifact-A
| \
| |
| |
Artifact-B | 1.60.0
| |
1.62.0 | |
| /
Artifact-C
If you could provide or link to a concise explination of how maven resolves these versions.
Answer: Maven works on the principle of nearest wins strategy while resolving the dependency conflicts, that means whichever version it finds nearer in the tree, it will take that version and ignore the other versions.
Multiple transitive dependencies can be excluded by using the <exclusion> tag for each of the dependency you want to exclude and placing all these exclusion tags inside the <exclusions> tag in pom. xml. You will need to mention the group id and artifact id of the dependency you wish to exclude in the exclusion tag.
By taking advantage of Maven's nearest definition logic, developers can override the version of a dependency by declaring it on the root pom. xml file.
See Introduction to the Dependency Mechanism:
With transitive dependencies, the graph of included libraries can quickly grow quite large. For this reason, there are some additional features that will limit which dependencies are included:
- Dependency mediation - this determines what version of a dependency will be used when multiple versions of an artifact are encountered. Currently, Maven 2.0 only supports using the "nearest definition" which means that it will use the version of the closest dependency to your project in the tree of dependencies. You can always guarantee a version by declaring it explicitly in your project's POM. Note that if two dependency versions are at the same depth in the dependency tree, until Maven 2.0.8 it was not defined which one would win, but since Maven 2.0.9 it's the order in the declaration that counts: the first declaration wins.
- "nearest definition" means that the version used will be the closest one to your project in the tree of dependencies, eg. if dependencies for A, B, and C are defined as A -> B -> C -> D 2.0 and A -> E -> D 1.0, then D 1.0 will be used when building A because the path from A to D through E is shorter. You could explicitly add a dependency to D 2.0 in A to force the use of D 2.0
This means that for your first example (and starting Maven 2.0.9) if artifact B is declared as a dependency in A before artifact C as follows:
<dependency>
<groupId>groupB</groupId>
<artifactId>projectB</artifactId>
</dependency>
<dependency>
<groupId>groupC</groupId>
<artifactId>projectC</artifactId>
</dependency>
then the dependency D declared in project B is chosen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With