【问题标题】:Grails beans in resources.groovy not injected into serviceresources.groovy 中的 Grails bean 未注入服务
【发布时间】:2017-02-23 13:28:22
【问题描述】:

使用 Grails 3.2.3/3.2.6,我遇到了一个问题,即 Resources.groovy 中配置的某些 bean 没有注入到该文件中也定义的服务中。 在现实生活中,这些配置的服务之一是在测试环境中由测试邮件服务交换的邮件,另一个是执行器服务,以确保异步进程在测试模式下同步完成。电子邮件是一个异步进程,它使用其他服务。

Here is a sample project

我有一个控制器 OneController:

class OneController {
    def theService
    def theOtherService

    def index() {
        render status:200, text: theService.getDataFromOtherService()
    }

    def direct() {
        render status:200, text: theOtherService.klet()
    }
}

resources.groovy 文件定义了def 的映射:

beans = {
    theService(OneService)
    theOtherService(AlternateSecondService)
}

服务非常简单:

class OneService {
    def theOtherService

    def getDataFromOtherService() {
        theOtherService.klet()
    }
}

和

class AlternateSecondService {

    def klet() {
        "Mariette"
    }
}

现在,如果我访问http://localhost:8080/one/index,我会在theOtherService.klet() 上得到一个空指针异常,因为theOtherService 为空。

如果我访问http://localhost:8080/one/direct,控制器确实正确注入了 bean 并且工作正常。

我目前通过使用Holders.getGrailsApplication().mainContext.theOtherService.klet() 避免了这个问题,但我想避免使用全局变量...

为什么第一个服务没有注入第二个?

【问题讨论】:

    标签: grails dependency-injection


    【解决方案1】:

    问题是您的theService bean 没有受到自动连接。实现这一目标的方法不止一种。您可以使用 Spring 注释,也可以在 resources.groovy 中执行类似的操作:

    beans = {
        theService(OneService) { bean ->
            bean.autowire = 'byName'
        }
        theOtherService(AlternateSecondService)
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多