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?
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.
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.
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.
I use the standard PostConstruct annotation:
class MyService { @PostConstruct def init() { // GORM accesible from here } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With