Maven Transitive Dependencies Explained

Apache Maven

14 Nov 2015

Apache maven is one of the widely used build tool in Java communitory and most of the developers are familiar with it. At times developers struggle to understand the dependencies or libraries being referenced at the compile time or at the run-time. This article explains how maven resolves direct or indirect referenced libraries and which one is given preference over another. 

Trasitive Dependencies

Any application being built references certain jars which are required for compilation and at runtime during execution. These dependencies are defined in the pom.xml file and can be transitive in nature which means project A depends on project AA which futher depends on project B and project C. Now technically project A dependes on projects AA, B and C. To add to the complexity project AA, B or C can be dependent on same library but different version of it. 

To complicate this further, different versions of dependencies might be getting referenced at different level and Maven needs to come up with the effective pom referencing only one version of a particular dependency.

How does Maven decide which version to use?

Maven uses “Dependency Mediation” algorithm to determine which dependency to be used when multiple versions of artifacts are present directly or indirectly. 

Shortest path

A dependecy at lower level has more priority over transitive dependency or dependency at higher level. If a dependency is referenced directly in the application’s pom file, that will be used instead of transitive dependency. In below example, xyz-1.0.jar would be used because that’s at level 1 whereas xyz-2.0.jar is at level 2. 


Declared First

If different versions of same dependency is used at same level, the one declared first is referenced. In below example, application pom file (pom.xml) contains xyz-1.0.jar before xyz-2.0.jar and hence 1.0.jar is referenced. 



Points to note

1. You can enforce any version by explicitly defining in the application pom file. This can be done to avoid any confusion or to ensure the version to be used if transitive dependencies are present. 

2. The transitive dependency can grow to any level and it doesn’t cause any problem unless circular dependency is occured. 

3. If certain version of dependency is getting picked by maven because of nearest first algorithm, you can exclude that dependency by using exclusion tag. This would let maven pick the next available version of the artifact.   

Leave a Reply

Your email address will not be published. Required fields are marked *