如何从普通的groovy类中访问数据源?注入不像服务那样工作.
原因是我需要从groovy类中进行一些手动数据库调用(即:使用groovy.sql.Sql类的SQL语句),因为我正在使用遗留数据库.
dataSource
是一种在services
使用时自动注入的豆子.默认情况下,所有bean都在grails工件(控制器,服务等)中自动连接.在你的情况下,你正在使用POGO,我想它会在里面src/groovy
.
您可以通过将dataSource
bean作为bean本身将其显式注入POGO类
//resources.groovy beans = { myPogo(MyPogo){ dataSource = ref('dataSource') } } //MyPogo.groovy MyPogo { def dataSource .... }
这是一项昂贵的操作.如果您已经访问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')
如果从Grails工件调用POGO类方法,则使用以下方法,而不是上述所有方法.例如:
//service class class MyService { def dataSource //autowired def serviceMethod(){ MyPogo pogo = new MyPogo() pogo.dataSource = dataSource //set dataSource in POGO } }