user1723095
user1723095

Reputation: 1219

How to use gradle properties in build.gradle

When I run this task:

task tmpTask << {
    project.properties.each {println "   $it"}
}

I see:

org.gradle.java.home=/usr/lib/jvm/java-6-oracle

But how to use this variable? I've tried both:

task tmpTask << {
    println org.gradle.java.home
    println project.properties.org.gradle.java.home
}

But none of this works. First print gives error:

Could not find property 'org' on task ':tmpTask'.

while second fails with:

Cannot get property 'gradle' on null object

Upvotes: 51

Views: 85038

Answers (4)

pswidersk
pswidersk

Reputation: 21

If you are using Gradle (8.10 version) with KotlinDSL (build.gradle.kts) it is recommended to use providers.gradleProperty() helper. For example:

println(providers.gradleProperty("org.gradle.java.home").get())

Please note that .get() method has to be used since it is a provider object.

REF

For some simpler names without special characters like pluginVersion it is also possible to use Kotlin delegated properties:

val pluginVersion: String by project
println(pluginVersion)

REF1 REF2

Upvotes: 2

linkaipeng
linkaipeng

Reputation: 503

From gradle.properties

Add prop to the file gradle.properties

hi1=hi

From CommandLine

Add -Pxxx end of command line.

./gradlew -q readPropertiesTask -Phi2=tete

Several properties:

./gradlew -q readPropertiesTask -Phi2=tete -Phi3=rr

How to read?

val propFromFile = project.properties["hi1"]
println("propFromFile = $propFromFile")

Upvotes: 12

al.
al.

Reputation: 1336

For anyone else's benefit. If the property you define is not dot separated, then you can simply refer to it directly.

In your gradle.properties:

myProperty=This is my direct property
my.property=This is my dotted property with\t\t tabs \n and newlines

In your build.gradle:

// this works
println myProperty
println project.property('my.property')

// this will not
println my.property

Upvotes: 31

JB Nizet
JB Nizet

Reputation: 691645

project.properties is a Map<String, ?>

So you can use

project.properties['org.gradle.java.home']

You can also use the property() method (but that looks in additional locations):

project.property('org.gradle.java.home')

Upvotes: 61

Related Questions