Posts Tagged ‘spring’

Spring Beans from the Grails console

Posted in Code on May 8th, 2012 by ataylor284 – Comments Off on Spring Beans from the Grails console

For Spring newbies, the objects Spring automatically instantiates and injects can be quite opaque. The grails console is great tool for understanding all the underlying Spring infrastructure.

This little snippet will list all the objects currently managed by Spring:

ctx.getBeanNamesForType(Object).sort().join('\n')

To access a bean by name:

ctx.getBean('beanName')

Or to get a list of services, taking advantage of the grails naming convention:

serviceNames = ctx.getBeanNamesForType(Object).findAll{it.endsWith('Service')}.sort().join('\n')

One of the more useful objects Spring can provide is the dataSource. You can use this for doing ad-hoc SQL manipulation without going through the Hibernate layer.

import groovy.sql.Sql
def dataSource = ctx.getBean('dataSource')
new Sql(dataSource).eachRow('select * from table') { row ->
    println row
}