我正在尝试从Service类发送邮件。
从UserCOntroller.groovy
我正在调用发送电子邮件的服务方法
maillingService.sendEmails(user)
MailingService.groovy
服务 :以下代码
class MailingService {
def sendEmails(User user) {
// def mailService // I ALSO TRIED WITH AND WITHOUT THIS ATTRIBUTE
mailService.sendMail {
to "fred@g2one.com","ginger@g2one.com"
from "john@g2one.com"
cc "marge@g2one.com", "ed@g2one.com"
bcc "joe@g2one.com"
subject "Hello John"
body 'this is some text'
}
}
我得到的错误是:
No such property: mailService for class: mypro.MailingService. Stacktrace follows:
Message: No such property: mailService for class: mypro.MailingService
编辑代码
def sendEmail(def u){
MailingService m = new MailingService()
m.sendEmails(u)
}
答案 0 :(得分:1)
你使用def mailService
走在正确的轨道上,但它需要是一个字段声明(在类级别),而不是方法内的局部变量:
class MailingService {
def mailService
def sendEmails(User user) {
mailService.sendMail {
to "fred@g2one.com","ginger@g2one.com"
from "john@g2one.com"
cc "marge@g2one.com", "ed@g2one.com"
bcc "joe@g2one.com"
subject "Hello John"
body 'this is some text'
}
}
}
此外,您应该不在控制器中自己实例化服务类,而应该像对上面的mailService
一样自动装配它:
class SampleController {
def mailingService
def sendEmail(User u) {
mailingService.sendEmails(u)
}
}