Java > Java Build Tools > Gradle > Dependency Management in Gradle
Gradle Dependency Management: Using Versions from Properties
This snippet shows how to manage dependency versions using properties in your build.gradle
file. This approach promotes consistency and simplifies updating versions across multiple dependencies.
build.gradle file with version properties
build.gradle
file. In this case, we define properties for the versions of JUnit, Apache Commons Lang, and Guava.junitVersion
property.commonsLangVersion
property to specify the version. The ${}
syntax is used to interpolate the property value into the string.
plugins {
id 'java'
}
group 'com.example'
version '1.0-SNAPSHOT'
ext {
junitVersion = '5.8.1'
commonsLangVersion = '3.12.0'
guavaVersion = '31.1-jre'
}
repositories {
mavenCentral()
}
dependencies {
implementation "org.apache.commons:commons-lang3:${commonsLangVersion}"
testImplementation "org.junit.jupiter:junit-jupiter-api:${junitVersion}"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:${junitVersion}"
api "com.google.guava:guava:${guavaVersion}"
}
test {
useJUnitPlatform()
}
Benefits of Using Version Properties
Using version properties offers several advantages:
build.gradle
file more readable by using named properties instead of hardcoded versions.
Real-Life Use Case
In a large project with many modules and dependencies, managing versions can become complex. Using version properties ensures that all modules use the same version of a library, preventing version conflicts and ensuring consistent behavior.
Best Practices
ext
block: This ensures that the properties are accessible throughout the build.gradle
file.
Alternatives
An alternative to the ext block is to define versions in the gradle.properties
file. This allows for externalising these versions and avoids cluttering the build.gradle
Pros
The pros of this solution are:
Cons
The cons of this solution are:
FAQ
-
Can I use version properties for plugins as well?
Yes, you can use version properties for plugins. However, the syntax is slightly different. You would need to use theversion
keyword within theplugins
block. -
How can I update a dependency version using this approach?
Simply change the value of the corresponding version property in theext
block, and Gradle will automatically update the dependency to the new version.