2017-02-23 66 views
1

使用Grails 3.2.3/3.2.6,我有一个问题,即Resources.groovy中配置的某些bean未注入到此文件中定义的服务中。 在现实生活中,这些配置服务之一是在测试环境中由测试邮件服务交换的邮件,另一个是执行程序服务以确保异步过程在测试模式下同步完成。该电子邮件是一个异步过程,它使用其他服务。Resources.groovy中的Grails 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()但我想避免使用全局变量避免这个问题...

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

回答

1

问题是您的theService bean未经过自动布线。有多种方式可以实现这一点。你可以使用Spring注释或者你可以在resources.groovy中做这样的事情:

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