groovy闭包参数

groovy闭包参数,groovy,closures,Groovy,Closures,以下使用grails邮件插件提供的sendMail方法的示例出现在中 我知道{}中的代码是作为参数传递给sendMail的闭包。我还知道to、subject和body都是方法调用 我试图弄清楚实现sendMail方法的代码是什么样子的,我的最佳猜测是这样的: MailService { String subject String recipient String view def model sendMail(closure) { cl

以下使用grails邮件插件提供的sendMail方法的示例出现在中

我知道{}中的代码是作为参数传递给sendMail的闭包。我还知道
to
subject
body
都是方法调用

我试图弄清楚实现sendMail方法的代码是什么样子的,我的最佳猜测是这样的:

MailService {

    String subject
    String recipient
    String view
    def model

    sendMail(closure) {
        closure.call()
        // Code to send the mail now that all the 
        // various properties have been set
    }

    to(recipient) {
        this.recipient = recipient
    }

    subject(subject) {
        this.subject = subject;
    }

    body(view, model) {
        this.view = view
        this.model = model
    }
}
这是合理的,还是我遗漏了什么?特别是,在闭包中调用的方法(
主题
正文
)是否必须是与
发送邮件
相同的类的成员

谢谢,
Don

我不确定sendMail方法的确切功能,因为我没有你提到的那本书。sendMail方法确实如您所描述的那样接受闭包,但它可能使用了一个闭包,而不是以正常方式执行。本质上,这是一种特定于域的语言,用于描述要发送的电子邮件

您定义的类不起作用的原因是闭包的作用域在声明它的地方,而不是在运行它的地方。因此,让您的闭包调用to()方法,它将无法在MailService中调用to方法,除非您将mail service的实例传递到闭包中

通过一些修改,您的示例可以使用常规闭包。对调用和

// The it-> can be omitted but I put it in here so you can see the parameter
service.sendMail {it->
    it.to "foo@example.org"
    it.subject "Registration Complete"
    it.body view:"/foo/bar", model:[user:new User()]
}
类中的sendMail方法应该如下所示

def sendMail(closure) {
    closure(this)
    // Code to send the mail now that all the 
    // various properties have been set
}

MailService.sendMail关闭委派:

 MailMessage sendMail(Closure callable) {
    def messageBuilder = new MailMessageBuilder(this, mailSender)
    callable.delegate = messageBuilder
    callable.resolveStrategy = Closure.DELEGATE_FIRST
    callable.call()

    def message = messageBuilder.createMessage()
    initMessage(message)
    sendMail message
    return message
}
例如,在MailMessageBuilder上执行以下操作的方法:

void to(recip) {
    if(recip) {
        if (ConfigurationHolder.config.grails.mail.overrideAddress)
            recip = ConfigurationHolder.config.grails.mail.overrideAddress
        getMessage().setTo([recip.toString()] as String[])
    }
}
void to(recip) {
    if(recip) {
        if (ConfigurationHolder.config.grails.mail.overrideAddress)
            recip = ConfigurationHolder.config.grails.mail.overrideAddress
        getMessage().setTo([recip.toString()] as String[])
    }
}