问题描述
如何从常规groovy类中访问数据源?注入不会像服务一样工作。
原因是我需要做一些手动数据库调用(即:使用groovy.sql的SQL语句.Sql类)从groovy类开始,因为我正在使用旧数据库。
通过将 dataSource bean明确地指向POGO类> // resources.groovy
beans = {
myPogo(MyPogo){
dataSource = ref('dataSource')
}
}
//MyPogo.groovy
MyPogo {
def dataSource
....
}
这是一项昂贵的操作。如果您已经在POGO中访问 applicationContext 或 grailsApplication ,那么您不需要像上面提到的那样创建一个bean。
dataSource bean可以直接从上下文中获取为:
// ctx是ApplicationContext
def dataSource = ctx.getBean('dataSource')
//或者如果grailsApplication可用
def dataSource = grailsApplication.mainContext.getBean('dataSource')
如果您正在调用POGO Grails工件的类方法然后使用下面的方法而不是所有上述方法。例如:
$ p $ //服务类
class MyService {
def dataSource // autowired
def serviceMethod(){
MyPogo pogo = new MyPogo()
pogo.dataSource = dataSource // set dataSource in POGO
}
}
How can I get access to the data source from within a normal groovy class? Injection doesn't work like it does with services.
The reason for this is that I need to do some manual database calls (ie: SQL statements using the groovy.sql.Sql class) from the groovy class since I'm working with a legacy database.
dataSource is a bean which gets auto injected in services when used. All beans are auto wired in grails artifacts (controllers, services etc) by default. In your case you are using a POGO and I suppose it would be inside src/groovy.
You can inject the dataSource bean explicitly to POGO class by making it a bean by itself
//resources.groovy beans = { myPogo(MyPogo){ dataSource = ref('dataSource') } } //MyPogo.groovy MyPogo { def dataSource .... }
This is an expensive operation. If you already are accessing applicationContext or grailsApplication in POGO then you need not create a bean as mentioned above.
dataSource bean can be directly fetched from the context as:
//ctx being ApplicationContext def dataSource = ctx.getBean('dataSource') //or if grailsApplication is available def dataSource = grailsApplication.mainContext.getBean('dataSource')
If you are invoking the POGO class methods from a grails artifact then use below approach than all of the above approaches. For example:
//service class class MyService { def dataSource //autowired def serviceMethod(){ MyPogo pogo = new MyPogo() pogo.dataSource = dataSource //set dataSource in POGO } }
这篇关于Grails:在常规的groovy类中获取数据源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!