March 10, 2009

Set bootstrap code for each environment in Grails

The Bootstrap.groovy file let's us define actions that need to be taken when the web application starts up. But what if we want to do certain actions in the development environment, but none in the production? We can use the GrailsUtil.environment property to determine the current environment and then assign actions per environment.

The following code will only add Message objects in the database for the development environment:

import grails.util.GrailsUtil

class BootStrap {

    def init = { servletContext ->
        switch (GrailsUtil.environment) {
            case "development":
                new Message(text: 'Hello world.').save()
                new Message(text: 'Another text message.').save()

     def destroy = {

Update for Grails 1.1 in this post.