我有这样的代码...
@Validateable
class RecipientsCommand {
...
EmailService emailService
void getEmailEligibleRecipients(Long accountId){
emailService.loadEligibleEmail(accountId)
}
}
资源
imports com.test.commands.RecipientsCommand
beans = {
recipientsCommand(RecipientsCommand){bean -> bean.autowire = true}
}
但是当我打电话时服务仍然总是为空
new RecipientCommand()
由于命令对象似乎是 View 和 Controller 之间的接口(interface),因此我将其创建,填充并将其传递给 View 。然后,我用它来解析和保存数据。如果我改成...
EmailService emailService = new EmailService()
一切正常。
最佳答案
自动连线仅在Grails为您创建实例时发生。您不能只是new RecipientCommand()
并期望Spring参与其中。如果您从Spring应用程序上下文中检索recipientsCommand
bean,它将被自动连接,并且如果RecipientCommand
由框架创建并作为参数传递给您的 Controller 操作,那么它也将被自动连接。调用new RecipientCommand()
构造函数将导致创建一个新实例,该实例不会自动连接。
编辑:
例子...
class SomeController {
def someAction(RecipientCommand co) {
// co will already be auto wired
// this approach does NOT require you to have defined the
// recipientsCommand bean in resources.groovy
}
}
class SomeOtherController {
def someAction() {
// rc will be autowired
// this approach requires you to have defined the
// recipientsCommand bean in resources.groovy
def rc = grailsApplication.mainContext.getBean('recipientsCommand')
}
}
class AnotherSomeOtherController {
def recipientsCommand
def someAction() {
// recipientsCommand will be auto wired
// this approach requires you to have defined the
// recipientsCommand bean in resources.groovy
}
}
class YetAnotherController {
def someAction() {
// rc will not be autowired
def rc = new RecipientCommand()
}
}
希望对您有所帮助。
关于spring - 在 Controller 内部构造时,将服务自动连线到Grails中的命令对象的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24411841/