Thursday, November 19, 2009

Getting Beans in Grails Console

It's convenient to run groovy snippets in Grails Console. At some time, these snippets might depend on some Service Object in your grails app. In Grails world, you can solve this kind of dependence using DI. Please check out "8.3 Dependency Injection and Services" in Grails reference document for more information. But now we are running groovy script in grails console, how can we get that service object we need? The reference document doesn't give us an answer directly.
Since Grails is based on Spring, we can resort to ApplicationContext. Now the problem is how to get the ApplicationContext instance. After reading "%GRAILS_HOME%/scripts/Console.groovy", you can find a bind-variable named "ctx", which points to the ApplcationContext Object. So, we can use it to get the dependent object used by the script in the console. Here is an example:
def executionService= ctx.getBean('executionService')
def processInstances= executionService.createProcessInstanceQuery().processDefinitionId('StateSequence-1').list()
def executions = processInstances.collect{
def activeNames= it.findActiveActivityNames()
}

No comments: