Tuesday, October 11, 2011

Initializing your Grails Services

by Richard Vowles

In one of my current Grails projects I need to do what I would normally use @PostConstruct for, but am unable to as usually GORM has not completed its additional methods by the time it comes to use them. So the general recommendation is to do it in the bootstrap - a technique I generally do not like as it means you cannot make it a best practice easily - just include a dependency and its always done.

Ideally I think I'll need to turn this into a plugin, but I hate source code plugins enough to just include the Bootstrap at the moment.

So this goes in your Grails conf, and its a slight modification of the one you find on Google - it checks the scope of the bean, singleton ones only are initialized.

import org.codehaus.groovy.grails.commons.GrailsClass
import org.codehaus.groovy.grails.commons.GrailsClassUtils

class BootStrap {
  def grailsApplication

  def init = { servletContext ->
    grailsApplication.serviceClasses.each { GrailsClass gClass ->

      String scope = GrailsClassUtils.getStaticPropertyValue(gClass.clazz, "scope")

      if (!scope || scope == "singleton") {
        def serviceBean = grailsApplication.mainContext.getBean(gClass.propertyName)

        if (serviceBean.metaClass.respondsTo(serviceBean, 'grailsInit')) {
          serviceBean.grailsInit()
        }
      }
    }
  }

  def destroy = {
  }
}



No comments: