我创建了一个服务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
在 NotifierService
在 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()
}
}
最佳答案
好的,这很清楚:)
如果你这样做
DbService dbService = new DbService()
那么依赖项将永远不会被spring填充。
你必须离开它
un-initialized
以便从应用程序上下文中注入(inject)服务:class MyJob {
DbService dbService // or def dbService
}
关于Grails:在服务中使用时无法在空对象上调用方法 sendEmail(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26258139/