如何使用 Spring Resource.groovy 正确注入 Grails 服务

2024-05-09

使用 Grails 2.2.1

我定义了以下 Grails 服务:

package poc

class TestService {
    def helperService
}

class HelperService {
}

我已经用过TestService如下 (resources.groovy):

test(poc.TestService) {
    
}

jmsContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) {
    connectionFactory = jmsConnectionFactory
    destinationName = "Test"
    messageListener = test
    autoStartup = true
}

除了自动注入之外一切正常helperService,正如 Grails 创建服务时所期望的那样。我可以让它工作的唯一方法是手动注入它,如下所示:

//added 
helper(poc.HelperService) {
}

//changed
test(poc.TestService) {
    helperSerivce = helper
}

问题是它的注入方式与 Grails 不同。我的实际服务非常复杂,如果我必须手动注入所有内容,包括所有依赖项。


声明于的 Beanresources.groovy是普通的 Spring bean,默认情况下不参与自动装配。您可以通过设置来做到这一点autowire明确地显示它们的属性:

aBean(BeanClass) { bean ->
    bean.autowire = 'byName'
}

在您的具体情况下,您不需要定义testService豆子在你的resources.groovy,只需从您的jmsContainer像这样的豆子:

jmsContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) {
    connectionFactory = jmsConnectionFactory
    destinationName = "Test"
    messageListener = ref('testService') // <- runtime reference to Grails artefact
    autoStartup = true
}

这记录在Grails 文档的“Grails 和 Spring”部分 http://grails.org/doc/latest/guide/spring.html在“引用现有 Bean”下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Spring Resource.groovy 正确注入 Grails 服务 的相关文章

随机推荐