如何从普通的 groovy 类中访问数据源?注入的工作方式与服务不同。
原因是我需要从 groovy 类执行一些手动数据库调用(即:使用 groovy.sql.Sql 类的 SQL 语句),因为我正在使用旧数据库。
dataSource
是一个自动注入的beanservices
使用时。默认情况下,所有 bean 都会自动连接到 grails 工件(控制器、服务等)中。在你的情况下,你使用的是 POGO,我想它会在里面src/groovy
.
您可以注入dataSource
通过使 bean 本身成为一个 bean 来显式地使用 POGO 类
//resources.groovy
beans = {
myPogo(MyPogo){
dataSource = ref('dataSource')
}
}
//MyPogo.groovy
MyPogo {
def dataSource
....
}
这是一项昂贵的操作。如果您已经在访问applicationContext
or grailsApplication
在 POGO 中,你不需要像上面提到的那样创建一个 bean。
dataSource
bean 可以直接从上下文中获取,如下所示:
//ctx being ApplicationContext
def dataSource = ctx.getBean('dataSource')
//or if grailsApplication is available
def dataSource = grailsApplication.mainContext.getBean('dataSource')
如果您从 grails 工件调用 POGO 类方法,则使用以下方法而不是上述所有方法。例如:
//service class
class MyService {
def dataSource //autowired
def serviceMethod(){
MyPogo pogo = new MyPogo()
pogo.dataSource = dataSource //set dataSource in POGO
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)