Sya*_*yam 1 grails grails-plugin grails-2.0 grails-services
我创建了一项服务 NotifierService
class NotifierService {
MailService mailService
def sendEmail(String email) {
mailService.sendMail {
to email
from "myemail@domain.com"
subject "Subject"
body "Some text"
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我试图在服务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
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
当我调用sendEmailmethod 时它工作正常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)
Run Code Online (Sandbox Code Playgroud)
我理解的是,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()
}
}
Run Code Online (Sandbox Code Playgroud)
好的,这很清楚然后:)
如果你这样做
DbService dbService = new DbService()
Run Code Online (Sandbox Code Playgroud)
那么依赖关系永远不会用spring填充.
你必须离开它,un-initialized以便从应用程序上下文中注入服务:
class MyJob {
DbService dbService // or def dbService
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6919 次 |
| 最近记录: |