Grails - Can't call service from Controller --> always get “Cannot invoke method on null object error”

≯℡__Kan透↙ 提交于 2019-12-13 12:52:13

问题


i have a grails application and i'm following the tutorial here:
http://www.grails.org/Services

i have some code like

import org.springframework.beans.factory.InitializingBean

class SubmitRequestService implements InitializingBean{
    def GrailsApplication1
    def setting

    void afterPropertiesSet(){
        this.setting = GrailsApplication1.config.setting
    }

    def void sendHistoricalContract(HistoricalContract hc_instance){
        //... blah blah whatever code      
    }
}

class SubmitRequestController {    
    def submitRequestService
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        // .... blah blah whatever code
        submitRequestService.sendHistoricalContract(historicalContractInstance)
    }    
}

No whatever i do, i can't seem to get the service to be injected into the controller. Whenever I get to the line where i call the service i get the error:

ERROR errors.GrailsExceptionResolver - Cannot invoke method sendHistoricalContract() on null object

What am i doing wrong?

Thanks in advance


回答1:


GrailsApplication1 looks weird - what's that coming from? If you want to access the GrailsApplication instance to get to the config, use a dependency injection for the grailsApplication Spring bean:

class SubmitRequestService implements InitializingBean {

   private setting

   def grailsApplication

   void afterPropertiesSet() {
       setting = grailsApplication.config.setting
   }

   void sendHistoricalContract(HistoricalContract hc_instance) {
      //... blah blah whatever code      
   }
}

My guess is that GrailsApplication1 is causing a problem with the service that's keeping it from being injected into the controller, but I would think that it'd blow up with an exception at startup. Try running grails clean to force a full recompile.




回答2:


I've run into this before.

I change it to grailsApplication1 and it worked.

Then you call:

this.setting = grailsApplication1.config.setting

Notice the case of the service




回答3:


Burt's answer is helpful (+1 to Burt) but in case others are following the tutorial here:
http://www.grails.org/Services
and experiencing the same issue i had, i want to make it explicit:

Services go in their own files under the Services directory, you do not combine them with controllers, even though it looks that way in the code examples

See Burt's comment above on additional resources to Services and the Spring Framework.



来源:https://stackoverflow.com/questions/4559270/grails-cant-call-service-from-controller-always-get-cannot-invoke-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!