在控制器内构建时,适当地将服务自动装配到Grails中的命令对象的方法

时间:2014-06-25 14:45:58

标签: spring grails

我有这样的代码......

@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()

一切正常。

1 个答案:

答案 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()
    }
}

我希望有所帮助。