Java Gradle Dependency management

One of the key feature of the build is managing the dependencies in the project. If we have to use a third party library, we declare that library in the build file i.e. build.gradle and then expect the build tool to download the library and put in the classpath of our project for consumption.

Let say we want to use google guava in our project, so we add the below dependency in the build.gradle file.

compile group: '', name: 'guava', version: '29.0-jre'

The above line will put the guava library in our project classpath and make the library available for us to use.

Dependency scope basically tells the gradle tool of our intention of when we want the library to be available. Lets go through one – by one.

  • Implementation
    It is used to declare dependencies that we don’t want to expose to consumers compile time. So it means that if we do not want the dependencies in our project to be exposed to the consumers of our project, we declare the dependency as implementation. The is the default scope and is an improvement over the compile scope. The compile scope is deprecated and will no longer be available in latest build scrips. So this scope avoids pollution of the transitive dependencies which will happen otherwise with compile scope.

  • api
    Use the api configuration do declare dependencies that are part of our API, i.e. for dependencies that we explicitly want to expose to our consumers. So if you want the dependency to be the part of the api for the consumers, then you declare the dependency as api.

  • compileOnly
    As the name suggests the dependencies which are supposed to be available only at compile time, such dependencies are marked compileOnly. E.g. of such a dependency is lombok. The lombok library is not required at runtime as it creates the required class files at compile time based on the annotations.

  • runtimeOnly
    Dependencies available only at the runtime are declared runtime dependencies.

testImplementation / testCompileOnly / testRuntimeOnly
testImplementation dependencies are only available during compilation and runtime of tests.

testCompileOnly dependencies are only available during compilation of tests and not at runtime.

testRuntimeOnly dependencies are only available during runtime of tests and not at compile time.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with
Get started
%d bloggers like this: