[英]groovy closure parameters
以下使用grails郵件插件提供的sendMail方法的示例出現在本書中 。
sendMail {
to "foo@example.org"
subject "Registration Complete"
body view:"/foo/bar", model:[user:new User()]
}
我理解{}中的代碼是一個閉包,它作為參數傳遞給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
}
}
這是合理的,還是我錯過了什么? 特別是,在閉包( to
, subject
, body
)中調用的方法是否必須與sendMail
屬於同一類的sendMail
?
謝謝,唐
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[])
}
}
我不確定sendMail方法究竟是什么,因為我沒有你提到的那本書。 sendMail方法確實在您描述時采用了閉包,但它可能使用構建器而不是以正常方式執行。 基本上,這將是用於描述要發送的電子郵件的域特定語言。
您定義的類不起作用的原因是閉包的范圍是聲明它不在其運行的位置。 因此,讓閉包調用to()方法,除非將郵件服務實例傳遞給閉包,否則它將無法在MailService中調用to方法。
通過一些修改,您的示例可以使用常規閉包。 呼叫的以下更改和
// 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.