Using PostConstruct annotation with Grails Services

27 / Aug / 2012 by Ankur Tripathi 1 comments

We can use PostConstruct with Grails Services and injected Spring Beans. This PostConstruct annotation can be used to annotate a method which needs to be executed after dependency injection to perform any initialization.

import javax.annotation.PostConstruct

class PostConstructDemoService {

    @PostConstruct
    private void init() {
          println "Initializing"
          //your initialization code goes here. e.g connect to some Messaging Service
     }
}

Check this for more details. We also have PreDestroy annotation.

Regards,
Ankur Tripathi
ankur@intelligrape.com

FOUND THIS USEFUL? SHARE IT

comments (1 “Using PostConstruct annotation with Grails Services”)

  1. Mike DeHaan

    While this does call the method marked with the annotation, this does not work when using domain objects within said method. If you attempt this, you receive:

    java.lang.IllegalStateException: Method on class [YourDomainObject] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

    To initialize a bean such as this, I had to utilize the BootStrap mechanism to call an init() method.

    Reply

Leave a comment -