Search code examples
javagradlecompilationdependencies

How to access nested dependencies at compilation time?


I have developed two libs: cms-lib and common-lib.

cms-lib is dependant on common-lib like this

# gradle.build of cms-lib

dependencies {
  implementation 'com.example.shared:common-lib:1.0-SNAPSHOT'
}

common-lib contains some public classes - f.e. com.example.shared.common.Content.java

The idea is that cms-lib is for third-party customer use (they should declare it in its gradle dependencies), while common-lib should be hidden from the customer (customer does not have to declare its gradle dependencies). So they just declare only cms-lib - like this:

# A
# build.gradle of a consumer of `cms-lib`

dependencies {
  implementation 'com.example.shared:cms-lib:1.0-SNAPSHOT'
}

That means that common-lib is nested the dependency of cms-lib.

I expect that public classes from the nested dependency common-lib, can be accessed by a customer of cms-lib. But it turns out they do not accessible as I get the compilation error:

> Task :compileJava FAILED
C:\temp\lib-test\src\main\java\consumer\Controller.java:3: error: package com.example.shared.common does not exist
import com.example.shared.common.Content;

It seems that in this case, public classes of support-lib is not available in compilation time (probably only at Runtime).

How to access nested dependencies at compilation time?


Solution

  • You will need to apply the java-library to the cms-lib project. Then you'll need to define common-lib in the api configuration in order for it to be available on the classpath of a consumer of cms-lib

    You can read more about api vs implementation in the docs for the Java library plugin.

    # gradle.build of cms-lib
    
    dependencies {
      api 'com.example.shared:common-lib:1.0-SNAPSHOT'
    }
    
    
    # A
    # build.gradle of a consumer of `cms-lib`
    
    dependencies {
      implementation 'com.example.shared:cms-lib:1.0-SNAPSHOT'
    }