Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a Gradle library to use its own version of dependency and not the project's one?

Tags:

java

gradle

There are these gradle projects:

  • main project (that uses library A and library B-version-1)
  • library A (that uses library B-version-2 declared as api, so the main project has both versions in dependencies B-v1 and B-v2).

When I run the app, the code from library A uses the version of library-B specified in the main project (B-v1), not the one it uses originally (B-v2).

Is there a way to force the library-A to use its own version of library-B?

like image 758
Reynard Avatar asked Oct 21 '25 00:10

Reynard


1 Answers

Is there a way to force the library-A to use its own version of library-B?

Yes, but how you achieve it depends on your goals:

  • if you want library-A to use its own version of library-B AND the main project to use its own version of library-B at the same time, you need to use Java Module System or do some dangerous tricks with class loading
  • if you want to force the version of library-B from library-A rather than the version from the main project, you just need to tell Gradle a few more words than usual - this is what my answer will be about

To understand why the v2 version of library-B was choose, you can read this manual:

Gradle will consider all requested versions, wherever they appear in the dependency graph. Out of these versions, it will select the highest one.

Assumption #1

You defined the version of library-B yourself and can change it in the main project.

So just change the version of library-B to the version that comes from library-A or just delete the dependency declaration -> the transitive dependency on library-B will be used

Assumption #2

You didn't define the version of library-B yourself and cannot change it in the main project. For example, this version comes from another library.

The are several ways to say Gradle which version of library-B it should use.

For example, using rich versions declaration, you define an implementation of library-B with the version you prefer:

// build.gradle.kts

dependencies {
    implementation("group.name:library-A:v1") // uses 'library-B' version 'v1'
    implementation("group.name:library-C:v1") // uses 'library-B' version 'v2'
    implementation("group.name:library-B") {
        version {
            strictly("v1")
        }
    }
}

Or using resolution strategy configuration:

// build.gradle.kts

configurations.all {
    resolutionStrategy {
        force "group.name:library-B:v1"
    }
}
like image 105
Maksim Eliseev Avatar answered Oct 22 '25 14:10

Maksim Eliseev