MissingMethodException: No signature of method for Grails Dynamic Method

In my last post, I described how you can use resources.groovy to create and initialize a class. However, you can get into trouble if the initMethod will access any of the dynamic methods that Grails introduces. If you are not careful, you may get an Exception like the following:

groovy.lang.MissingMethodException: No signature of method: static Thing.count() is applicable ...

Thing is a Grails Domain class and Grails adds the count method dynamically. So, what is the problem? It turns out to be just a matter of timing. The initMethod of our Spring created and initialized Java class is getting called prior all of the dynamic methods getting added to our Domain classes.

The fix is easy, once you understand what is going on. The Grails team has a hook that you can take advantage of. You will find examples of it’s use in the area of creating and saving instances of Domain objects on various web sites. The hook is the init method in BootStrap.groovy, which will be found in /grails-app/conf.

Below is an example of the default BootStrap class.

1
2
3
4
5
6
7
class BootStrap {
 
     def init = { servletContext ->
     }
     def destroy = {
     }
}

The init method of BootStrap will be called when Grails has completely initialized your application and all of the dynamic methods are available. This is the safe place to invoke the initMethod of your Spring created class. Below is a solution to the problem, which uses Grails auto-wire to get a reference to the Spring created class.

1
2
3
4
5
6
7
8
9
class BootStrap {
    def example
 
     def init = { servletContext ->
         example.init()
     }
     def destroy = {
     }
}

Tags:

Leave a Reply

You must be logged in to post a comment.