我创建了一个服务NotifierService
class NotifierService {
MailService mailService
def sendEmail(String email) {
mailService.sendMail {
to email
from "myemail@domain.com"
subject "Subject"
body "Some text"
}
}
}
然后,我试图在服务sendEmail
中的另一个方法中调用方法updateUser
DbService
class DbService {
NotifierService notifierService
def updateUser(){
//Some Logic
//Get userObject
def email = userObject.email
//Send email
try {
notifierService.sendEmail(email)
} catch (Exception e) {
e.printStackTrace()
}
}
//Other methods
.
.
.
}
当我调用sendEmail
方法时它工作正常BootStrap
,但是当我使用它时出现以下错误DbService
| Error java.lang.NullPointerException: Cannot invoke method sendMail() on null object
| Error at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:77)
| Error at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
| Error at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
| Error at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:32)
| Error at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
我知道在mailService
inNotifierService
中使用它时 in 没有初始化DbService
。我该如何解决?
在DbService
grails-job 中实例化
class MyJob {
DbService dbService = new DbService()
static triggers = {
// start delay: 30000 (30sec), repeat: 120000 (2*60*1000 = 2min)
simple name:'myJobTrigger', startDelay:30000, repeatInterval: 120000, repeatCount: -1
}
def execute() {
println "*******************************************************"
println "MyJob: "+new Date()
println "*******************************************************"
dbService.updateUser()
}
}