Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call an initialization function on a Grails service?

Tags:

I have a Grails service that is a wrapper around a rather complicated singleton object. I'd like to do some initializing to populate the singleton when the service is started. It would be nice if there was some kind of init() function that would be automatically called by the service when it starts, but I have found no such thing.

Is there a clean way to do this?

like image 515
Spike Williams Avatar asked Apr 11 '12 19:04

Spike Williams


People also ask

What is initialization function?

Initialization function ( InitFcn ) is a type of callback that is executed or evaluated at the beginning of model compilation. You can use InitFcn in a model (model InitFcn ) or a block (block InitFcn ). Note. Variant controls can be defined only in model InitFcn callback.

What is a Grails service?

Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.


2 Answers

You can implement InitializingBean as described by @Saurabh but that fires rather early in the Grails startup process, so while it works, the are some things that won't be available yet, for example you can't call GORM methods in domain classes because that happens after bean initialization. If InitializingBean isn't sufficient you can call an initialization method from BootStrap.groovy, e.g.

class BootStrap {     def myService     def init = { servletContext ->       myService.initialize()    } } 

and you can call the method initialize or whatever you want in the service class. You can also do the initialization work directly in BootStrap if you don't want that code in the service class.

like image 123
Burt Beckwith Avatar answered Oct 08 '22 15:10

Burt Beckwith


I use the standard PostConstruct annotation:

class MyService {          @PostConstruct     def init() {       // GORM accesible from here     }  } 
like image 21
IsidroGH Avatar answered Oct 08 '22 17:10

IsidroGH