Spicy Spring: Using Groovy Configuration As PropertySource

We have many ways to provide configuration properties to a Spring (Boot) application. We can add our own custom configuration properties format. For example we can use Groovy’s ConfigObject object to set configuration properties. We need to read a configuration file using ConfigSlurper and make it available as a property source for Spring. We need to implement two classes and add configuration file to support a Groovy configuration file in a Spring application.

First we need to write a class that extends the PropertySource in the package org.springframework.core.env. This class has methods to get property values based on a given key. There are already some subclasses for specific property sources. There is for example also a MapPropertySource class. We will extend that class for our implementation, because we can pass our flattened ConfigObject and rely on all existing functionality of the MapPropertySource class:

Next we must implement a class that loads the configuration file. The configuration file must be parsed and we must our ConfigObjectPropertySource so we can use it in our Spring context. We need to implement the PropertySourceLoader interface, where we can define the file extensions the loader must be applied for. Also we override the load method to load the actual file. In our example we also add some extra binding variables we can use when we define our Groovy configuration file.

Finally we need to add our ConfigObjectPropertySourceLoader to a Spring configuration file, so it used in our Spring application. We need to create the file spring.factories in the META-INF directory with the following contents:

Now when we create a Spring application with all our classes and configuration file in the classpath we can provide an application.groovy file in the root of the classpath:

Written with Spring Boot 1.3.5.RELEASE

Original blog post

This entry was posted in Coding, Groovy, Spring 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.

3 thoughts on “Spicy Spring: Using Groovy Configuration As PropertySource

  1. Pingback: Java Web Weekly, Issue 132 | Baeldung

Leave a Reply

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