Search

Dark theme | Light theme

September 28, 2015

Grails Goodness: Using Random Values For Configuration Properties

Since Grails 3 we can use a random value for a configuration property. This is because Grails now uses Spring Boot and this adds the RandomValuePropertySource class to our application. We can use it to produce random string, integer or lang values. In our configuration we only have to use ${random.<type>} as a value for a configuration property. If the type is int or long we get a Integer or Long value. We can also define a range of Integer or Long values that the generated random value must be part of. The syntax is ${random.int[<start>]} or ${random.int[<start>,<end>}. For a Long value we replace int with long. It is also very important when we define an end value that there cannot be any spaces in the definition. Also the end value is exclusive for the range.
If the type is something else then int or long a random string value is generated. So we could use any value after the dot (.) in ${random.<type>} to get a random string value.

In the following example configuration file we use a random value for the configuration properties sample.random.password, sample.random.longNumber and sample.random.number:

# File: grails-app/conf/application.yml
...
---
sample:
    random:
        password: ${random.password}
        longNumber: ${random.long}
        number: ${random.int[400,420]}
...

Next we have this simple class that used the generated random values and displays them on the console when the application starts:

// File: src/main/groovy/com/mrhaki/grails/random/RandomValuesPrinter.groovy
package com.mrhaki.grails.random

import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.stereotype.Component

@Component
class RandomValuesPrinter implements CommandLineRunner {

    @Value('${sample.random.password}')
    String password

    @Value('${sample.random.number}')
    Integer intValue

    @Value('${sample.random.longNumber}')
    Long longValue

    @Override
    void run(final String... args) throws Exception {
        println '-' * 29
        println 'Properties with random value:'
        println '-' * 29

        printValue 'Password', password
        printValue 'Integer', intValue
        printValue 'Long', longValue
    }

    private void printValue(final String label, final def value) {
        println "${label.padRight(12)}: ${value}"
    }

}

When we run our Grails application we can see the generated values:

$ grails run-app
...
-----------------------------
Properties with random value:
-----------------------------
Password    : 018f8eea05470c6a9dfe0ce3c8fbd720
Integer     : 407
Long        : -1201232072823287680
...

Written with Grails 3.0.8.