Har*_*cle 7 sql grails groovy datasource code-injection
如何从普通的groovy类中访问数据源?注入不像服务那样工作.
原因是我需要从groovy类中进行一些手动数据库调用(即:使用groovy.sql.Sql类的SQL语句),因为我正在使用遗留数据库.
dma*_*tro 17
dataSource是一种在services使用时自动注入的豆子.默认情况下,所有bean都在grails工件(控制器,服务等)中自动连接.在你的情况下,你正在使用POGO,我想它会在里面src/groovy.
您可以通过将dataSourcebean作为bean本身将其显式注入POGO类
//resources.groovy
beans = {
myPogo(MyPogo){
dataSource = ref('dataSource')
}
}
//MyPogo.groovy
MyPogo {
def dataSource
....
}
Run Code Online (Sandbox Code Playgroud)
这是一项昂贵的操作.如果您已经访问applicationContext或grailsApplication在POGO中,那么您不需要创建如上所述的bean.
dataSource bean可以直接从上下文中获取:
//ctx being ApplicationContext
def dataSource = ctx.getBean('dataSource')
//or if grailsApplication is available
def dataSource = grailsApplication.mainContext.getBean('dataSource')
Run Code Online (Sandbox Code Playgroud)
如果从Grails工件调用POGO类方法,则使用以下方法,而不是上述所有方法.例如:
//service class
class MyService {
def dataSource //autowired
def serviceMethod(){
MyPogo pogo = new MyPogo()
pogo.dataSource = dataSource //set dataSource in POGO
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8987 次 |
| 最近记录: |