Home > Net >  import dependencies from another module
import dependencies from another module

Time:10-23

I think I am missing some point in how dependencies management works in gradle. Let's say I have the following project structure:

project
---api
------api-commons
------api-v1
------api-v2
------api-v3

where all api* directories are modules. All api-v* need a particular dependency (let's say common-dependency).

My aim would be to import it in api-commons build.gradle file:

dependencies {
   implementation 'common-dependency'
}

while in the build.gradle files of the other modules api-v* put:

dependencies{
   implementation project(':api:api-commons')
}

I would expect this to work but it doesn't. The code in the api-v* modules simply acts like the dependency is not declared. Indeed, if I import the dependency in the single modules, the code works as expected.

Am I doing a wrong assumption? Doesn't the dependency inheritance work like that?

CodePudding user response:

Declaring a dependency in the implementation configuration conceptually means it is internal to the module (it is used in the implementation but not part of the public API). Such a dependency will not be exposed to the compile classpath of consumers, though it will still be on the runtime classpath.

An advantage of this way of modelling dependencies is that you do not need to recompile consuming projects if an implementation dependency changes. Another is that by encapsulating them, it is less likely that a consumer will start depending on them directly and then breaking if you change them.

If you want to expose the dependency to consumers, you have to declare it as part of the API for the module. You do that by applying the java-library plugin and using the api configuration.

Example:

// api-commons/build.gradle
plugins {
  id 'java-library'
}

dependencies {
   api 'common-dependency'
}

Read more about it in the Gradle user guide

  • Related