【问题标题】:How to PROPERLY inject Grails services using Spring resource.groovy如何使用 Spring resource.groovy 正确注入 Grails 服务
【发布时间】:2013-05-30 21:59:00
【问题描述】:

使用 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 不同。我的实际服务非常复杂,如果我必须手动注入所有内容,包括所有依赖项。

【问题讨论】:

  • 如果使用适当的命名法,Grails 服务会默认注入。您不需要在resources.groovy 中输入服务。您实际面临的问题是什么?

标签: spring grails dependency-injection resources javabeans


【解决方案1】:

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

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

在您的具体情况下,您不需要在 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
}

这在 "Grails and Spring" section of the Grails Documentation 的“引用现有 Bean”下进行了记录。

【讨论】:

  • 另外,按名称自动装配只会在@AutowiredSpring注解标记的bean属性上完成
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 2020-12-03
  • 1970-01-01
  • 2023-04-10
  • 2016-01-30
  • 1970-01-01
  • 2011-07-14
相关资源
最近更新 更多