我有这样的代码......
@Validateable
class RecipientsCommand {
...
EmailService emailService
void getEmailEligibleRecipients(Long accountId){
emailService.loadEligibleEmail(accountId)
}
}
resource.groovy
imports com.test.commands.RecipientsCommand
beans = {
recipientsCommand(RecipientsCommand){bean -> bean.autowire = true}
}
但是当我打电话
时,服务仍然是空的new RecipientCommand()
由于Command对象似乎是视图和控制器之间的接口,我正在创建它,填充它并将其传递给视图。然后我用它来解析和保存数据。如果我换到......
EmailService emailService = new EmailService()
一切正常。
答案 0 :(得分:3)
只有当Grails为您创建实例时才会发生自动布线。你不能仅仅new RecipientCommand()
并期望Spring参与其中。如果从Spring应用程序上下文中检索recipientsCommand
bean,它将自动连接,如果RecipientCommand
由框架创建并作为参数传递给控制器操作,那么它也将自动连接。调用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()
}
}
我希望有所帮助。