Calling A Service From The Grails Console

I’m doing my first project in Grails and intend to blog some of thing things I’m learning.

During development, the grails console is very useful for testing specific pieces of code without having to go through your whole system to get to that particular bit of code.

For the most part, you can just enter grails commands and hit execute. But apparently dependency inject doesn’t happen in the console. So there’s a bit of a trick to execute a service from the console.

If you had a service named MySecretService with a function named secretSquirell, you could access it via dependency injection in a domain class, a controller or another service by first adding

def mySecretService

then later you can say
def result = mySecretService.secretSquirell()

But to test in the console you need to do this:

def service = ctx.getBean("mySecretService")
def result = service.secretSquirell()

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]