Configuration
Learn how to configure tasks in Gradle.
We'll cover the following
Configuring a task
Once you’ve added some plugins, configure some of the properties of a task for your purposes.
For example, specify a version of Gradle for the Gradle wrapper
task:
task wrapper(type: Wrapper) {
gradleVersion = '5.1'
}
The properties available depend on what task we are configuring.
Extra configuration
To provide extra properties within your Gradle build file, use the ext
method. We can define any
arbitrary values within the closure, and they will be available throughout your project.
We can also apply properties from other Gradle build files. For example:
ext {
apply from: 'props/another.gradle'
myVersion = '1.2.3'
}
The properties defined within this closure can be used in your tasks.
Maven dependencies
Every Java project tends to rely on many open-source projects to be built. Gradle can use mavenstyle
repositories, so we can easily include your dependencies using a simple DSL like in the following example:
plugins {
id 'java'
}
sourceCompatibility = "11"
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile 'com.google.guava:guava:14.0.1'
compile 'org.bitbucket.dollar:dollar:1.0-beta3'
testCompile group: 'junit', name: 'junit', version: '4.+'
testCompile "org.mockito:mockito-core:1.9.5"
}
This build script uses sourceCompatibility
to define the Java source code version of 11 (which is used during compilation). Next, it tells Maven to use the local repository first (mavenLocal
) then Maven Central.
In the dependencies
block, this build script defines two dependencies
for the compile scope and two for the testCompile
scope. Jars in the testCompile
scope are only used by tests and won’t be included in any final products.
Gradle can use a compact syntax of groupId:artifactId:version
, so “com.google.guava:guava:14.0.1” becomes “groupId = com.google.guava, artifactId = guava, version = 14.0.1.”
The line for JUnit shows the more verbose style for defining dependencies. Also, “4.+” means using the highest version starting with “4.”
We can also specify our own Maven repository by calling maven with a closure supplying the appropriate parameters (at least a URL). For example, in the repositories section:
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url = "$nexus/content/groups/public"
credentials {
username 'deployment'
password deploymentPassword
}
}
The second example demonstrates using a secured maven repository. It also demonstrates using the variables nexus
and deploymentPassword
, which could (probably should) be stored in a
gradle.properties
file.
Get hands-on with 1400+ tech skills courses.