Andrew
Andrew

Reputation: 2363

Access DataSource in groovy class in grails dynamically

I need to make a direct sql call using groovy.sql in a non-domain class.

Imagine I have 10 different datasources defined.

I need to be able to figure out which one to use so that I can get the server to do connection pooling for me. I don't want to have to hack something where I need to inject all the datasources into a service and pass them around until I need them.

I want code that looks kind of like this.

Integer sn = getShardNumber(somedata)
def dataSourceName = "shard" + sn.toString()
def dataSource = SystemMagic.getDataSource(dataSourceName)
def sql = new Sql(dataSource)
 ....

How do I make the "SystemMagic" call as above?

Thanks, andrew

Upvotes: 1

Views: 890

Answers (1)

tim_yates
tim_yates

Reputation: 171084

This is the way it worked in Grails 1.3.7... I'm yet to migrate to 2.0 however...

Assuming this is in a Service

import org.springframework.context.*

class MyService implements ApplicationContextAware {
  ApplicationContext  applicationContext

  ...

  def getDataSource( name ) {
    applicationContext.getBean( name )
  }

  ...
}

Upvotes: 1

Related Questions