Marco
Marco

Reputation: 15929

Store and use application configuration settings in database for a Grails application?

we currently use configuration files to store application settings. I was wondering if it is possible to store these settings inside the database and if so how to achieve this?

Greetings

Upvotes: 2

Views: 1139

Answers (2)

ibaralf
ibaralf

Reputation: 12528

This is can be done with BootStrap.groovy. So following Jarred's answer, create a domain class of the configuration data you would like to store and then inside the BootStrap.groovy file, put these values. What this does is if the configuration values does not exists, it will create it, if it exists will not do anything.

Then you can access your configuration values using the domain class. I'm assuming you want to do this because grailsApplication.config... can sometimes become unruly.

Domain-Class MyConfig.groovy:

class MyConfig {
  String type
  String name
  String value
}

BootStrap.groovy:

def myConfig = MyConfig.findByName("path") ?: new MyConfig(
    type: "Path"
    name: "path"
    value: "/var/tmp"
).save(failOnError: true)

Upvotes: 1

Jarred Olson
Jarred Olson

Reputation: 3243

You can store whatever you want in the database and read it out using a Domain class. This is especially useful if you want to be able to make changes to things without having to redeploy new code. But realize that you will incur a database hit every time the property is accessed.

You can set up a ConfigurationService with:

ConfigurationService {
    static def configurationValues

    def getConfigurationValues() {
        if(configurationValues == null) {
            refreshConfigurationValues()
        }
        configurationValues
    }

    def refreshConfigurationValues() {
        configurationValues = //go get the values out of the database
    }
}

Then you can add a Controller/Action to force the refresh when necessary

ConfigurationController {

    def configurationService

    def refreshConfiguration = {
        configurationService.refreshConfigurationValues()
        render "Ahhh... That's refreshing :)"
    }
}

Now you can refresh your config values by invoking: "http://yoururl/appName/configuration/refreshConfiguration"

Upvotes: 3

Related Questions