Article
0 comment

Playing around with services in grails console

Suppose you have a grails project and have witten a service doing some database magic to pull together data. Now suppose the very unlikely case that it’s not running that smooth than you thought. To expel the black magic you probably would like to use the grails console to play around with your domain classes and services. Using a service is as simple as importing the domain class and using it:

import myproject.Domainclass
def instance=Domainclass.get(3)
println instance.id+"\t"+instance.name

The service classes however are not that accessible to manipulation. You need to request the service bean instance by name from the application context named ctx:

def mcs=ctx.getBean("myCoolService")
def allThings=mcs.getAllThings()

Remember to use the (lowercase) instance name when calling getBean() just as it would be injected into your controller:

class GraphController {
    MyCoolService myCoolService
}

Pulling the strings together you can do more complex tests:

import myproject.Domainclass

def mcs=ctx.getBean("myCoolService")
def instance=Domainclass.get(3)
println instance.id+"\t"+instance.name
println "-----------------------------------------"
def allThings=mcs.getAllThings()
allThings.each { n -> println n.id+"\t"+n.thingstype+"\t\t"+n.name }

Hope that helps. As always: in case of questions or corrections / additions please leave a comment :)

Leave a Reply

Required fields are marked *.