Friday, March 13, 2009

calling dynamic domain finders in Grails

Had the need today for calling a Grails domain class finder method outside of the normal artifact setup. There's a singleton I wanted to write to cache certain hunks of data from the database. It'd be very convenient to have access to those domain classes to save me the pain of writing boilerplate Hibernate config and EJB classes. So, here's what ended up working.

I injected a GrailsApplication reference into my bean and created a closure that I passed to a new Groovy Timer instance. Inside the closure I'm able to invoke the dynamic finders on the domain classes because I can fetch a new instance this way:

def person_class = grailsApplication.getArtefact("Domain","Person")
def person_instance = person_class.newInstance()


That's simple enough, to actually call the finders (in this case "list") the next step was:

def results = person_class.metaClass.invokeStaticMethod(person_instance,'list',null)


Next plans are to create a generic way of exposing the ability to call the dynamic methods so that any Groovy class in the app has has access to them.

No comments: