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

vla*_*tax 6 grails resources spring dependency-injection javabeans

使用Grails 2.2.1

我定义了以下Grails服务:

package poc

class TestService {
    def helperService
}

class HelperService {
}
Run Code Online (Sandbox Code Playgroud)

我使用了TestService如下(resources.groovy):

test(poc.TestService) {

}

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

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

//added 
helper(poc.HelperService) {
}

//changed
test(poc.TestService) {
    helperSerivce = helper
}
Run Code Online (Sandbox Code Playgroud)

问题是它没有像Grails那样注入方式.我的实际服务非常复杂,如果我必须手动注入所有内容,包括所有依赖项.

cod*_*ark 9

在resources.groovy中声明的bean是普通的Spring bean,默认情况下不参与自动装配.您可以通过显式设置autowire属性来实现:

aBean(BeanClass) { bean ->
    bean.autowire = 'byName'
}
Run Code Online (Sandbox Code Playgroud)

在您的特定情况下,您不需要在resources.groovy中定义testService bean,只需从jmsContainer bean中设置对它的引用,如下所示:

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

这在"引用现有Bean"下的Grails文档"Grails and Spring"部分中有记录.