Friday, February 11, 2011

Creating a Auto Initialising Grails Service

  Many a times while developing a Grails based application, we come across a situation where we need to declare a service which needs to be initialized with some values in its Instance variable at runtime during Application bootup time.
  Grails Services are Singleton by default. Meaning that once initialised using its NEVER gonna get re-initialized again till the time app is running. This is expected behavior as well, just imagine how expensive it would be when Services are not singleton. Controllers of Grails are anyways NOT singleton as its scope is Request, so we can NOT really afford to have Service non-singleton as well !!
  Here is the way you can create such a Initialising Service:

import org.springframework.beans.factory.InitializingBean

class MyService implements InitializingBean {

    Long someVariableToBeInitialzed

    void afterPropertiesSet() {
            println "Initializing MyService...."

            /* Calculate dynamic value u want to set here for all the required instance Variables  */
            someVariableToBeInitialzed = ........

   1. These Services beans will be initialised before "BootStrap,groovy" gets executed !! So beware that if you putting / settingup some data in bootstrap, that these service might use while initializing, you will be facing some issues like NPE etc. based on the type of data you setting-up in BootStrap.
      Although not a great and neat solution, but in such situations, rather than making service Initializable, you make a simple function in service and call it from Bootstrap after you have put the code to satisfy the dependencies for the service. You can refer to the service from BootStrap just like you do it in Controller. ie. by putting following line at the top of the class in BootStrap.groovy
    def xxxService

No comments: