开发者

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

i have a grails application and i'm follow开发者_StackOverflow社区ing 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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜