Gradle Goodness: Create Objects Using DSL With Domain Object Containers

Gradle offers the NamedDomainObjectContainer class to create a collection of objects defined using a clean DSL. The only requirement for the objects we want to create is that they have a constructor that takes a String argument and a name property to identify the object. The value for the name property must be unique within the collection of objects. We create a new instance of a NamedDomainObjectContainer with the container method of the Gradle Project class. We can add the NamedDomainObjectContainer instance to the extensions property of our project, so we can use a DSL to create instances of objects that need to be in the NamedDomainObjectContainer object in our project.

The following code shows a simple build script in which we want to create a collection of Product objects. The creation of the NamedDomainObjectContainer object is done in a plugin so we only have to apply the plugin to use the DSL to create Product objects:

We can run the reportProducts task to see the name and price properties of the Product instances:

Written with Gradle 2.11.

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 *