1

我创建了一个服务NotifierService

class NotifierService {

    MailService mailService

    def sendEmail(String email) {
        mailService.sendMail {
            to email
            from "myemail@domain.com"
            subject "Subject"
            body "Some text"
        }
    }
}

然后,我试图在服务sendEmail中的另一个方法中调用方法updateUserDbService

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)

我知道在mailServiceinNotifierService中使用它时 in 没有初始化DbService。我该如何解决?

DbServicegrails-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()
    }
}
4

1 回答 1

5

好的,这很清楚:)

如果你这样做

DbService dbService = new DbService()

那么依赖项将永远不会被spring填充。

您必须保留它,un-initialized以便从应用程序上下文中注入服务:

class MyJob {
  DbService dbService // or def dbService
}
于 2014-10-08T13:47:16.900 回答