77

This question is about to clarify what exactly a transitive dependency is and how it works at very high level in Maven.

My definition: in a dependency tree like A --> B --> C, C is a transitive dependency for A. Assume B has scope compile within A.

If C has scope compile within B, then declaring B as dependency of A suffices to build A with Maven. But if C has scope provided within B then, when Maven builds A, the building will not automatically compile A against C unless A declares C among its dependencies.

Is this correct?

2240
  • 1,547
  • 2
  • 12
  • 30
Johan
  • 3,561
  • 9
  • 29
  • 45
  • What does against mean in 'compile A against C'? I'm a mvn beginner and I noticed this example is exactly what I didn't know. I'm thinking A against C as 'using some `import C.someClass` at A.someClass'. Is this correct? – rado Aug 22 '18 at 16:11
  • @GabrielRado I guess what he means is if C has scope _provided_ within B, then the artifact generated will not include C. This statement _import C.someClass at A.someClass_ will work when you have C in your classpath at compile time but if for some reason is NOT provided at runtime, you'll get no class def found exception. – Boss Man Jan 18 '19 at 22:18

3 Answers3

81

Your assumption is correct.

There are two types of Maven dependencies:

  • Direct: These are dependencies defined in your pom.xml file under the <dependencies/> section.

  • Transitive: These are dependencies that are dependencies of your direct dependencies.

Dependencies with provided scope are meant to:

  • Either be excluded from the final artifact (for example, for war files you would not want to include servlet-api, servlet-jsp, etc)
  • Or overriden -- where the project that inherits these defines a version and/or overrides the scope
carlspring
  • 31,231
  • 29
  • 115
  • 197
  • What if C can't be resolved? How would I know B->C so I can change B's version? I checked parent pom and effective pom it's not there. – Philip Rego Apr 03 '19 at 17:50
  • If an artifact's POM file cannot be resolved from the remote repository, Maven will throw an error while trying to build the dependency tree. – carlspring Apr 03 '19 at 23:54
2

As an example, if we added JUnit as a dependency in pom.xml under <dependencies> tag. It will download the other hamcrest-core-1.3.jar file and it is under Maven Dependencies, This .jar file can be called Transitive dependency.

enter image description here

Resource:- https://youtu.be/ypVE8EgDzzI

Supun Sandaruwan
  • 1,814
  • 19
  • 19
-8

A dependency that should be included when declaring project itself is a dependency

mahsa
  • 58
  • 1
  • 7