我创建了一项服务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
。我该如何解决?
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()
}
}
在grails-job
{{1}}
答案 0 :(得分:5)
好的,这很清楚:)
如果你这样做
DbService dbService = new DbService()
那么依赖关系永远不会用spring填充。
您必须保留un-initialized
,以便从应用程序上下文中注入服务:
class MyJob {
DbService dbService // or def dbService
}