Gradle Goodness: Lazy Project Property Evaluation

Sometime we need to define a project property in our Gradle build file for which the value must be evaluated later than the assignment. We can do this in different ways in Gradle. For example for a String type property we can rely on Groovy’s support for lazy String evaluation. If the property is of a different type we can use Closure to define the value. The Closure code is not executed during the configuration phase directly, but we can write code to invoke the Closure at the right moment and get the value. Finally we can use the afterEvaluate method of the Project class to define a lazy property. Let’s look at the different options we have with some code samples.

First we look at a lazy String property. We illustrate this with an example of a multi-project build with the following layout:

In our settings.gradle file we define the projects we want to be part of the root project:

Let’s create a build file with a lazy property buildVersion:

If we run the displayBuildVersion task we get the following output:

If we have a property of another type than String we can use another mechanism to support lazy properties. We use a Closure to define the value and then invoke the Closure to calculate the value at a later time. In the next build script we add a support method lazyProperty to check if the property is defined with a Closure. If so we execute the Closure to calculate the value. Any other type is return as-is.

Let’s run the displayBuildVersion task and look at the output:

Finally we use the afterEvaluate method:

When we run the displayBuildVersion task and look at the output we see expected results:

In our simple examples we used the lazy project property only in one task. We could have simply evaluated the value in the task definition as it is the only place where it is used. But if a property is used by other tasks and code in our build script we can rely on the mentioned solutions in this blog post.

Written with Gradle 3.0.

Original blog post

This entry was posted in Coding, Gradle and tagged by mrhaki. Bookmark the permalink.

About mrhaki

My name is Hubert A. Klein Ikkink also known as mrhaki. I work at the great IT company JDriven. Here I work on projects with Groovy & Grails, Gradle and Spring. At JDriven we focus on SpringSource technologies. All colleagues want to learn new technologies, support craftmanship and are very eager to learn. This is truly a great environment to work in. You can contact me via Google+ or @mrhaki.

Leave a Reply

Your email address will not be published. Required fields are marked *