Pramod Krs Palla
Pramod Krs Palla

Reputation: 13

Facing Null Pointer Exception: Cannot invoke method firstMethod() on null Object : Grails 3.2.10

I wrote a simple rest-api Controller in Grails 3.2.10 version. Below are my system configurations. Created application is also rest-api profile.

Grails Version: 3.2.10 Groovy Version: 2.4.10 JVM Version: 1.8.0_131

Sample code written is as follows: Controller:

package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def index() {
        def loginService
        def val = loginService.firstMethod()

        render 'hello World' + val
     }
   }

Service :` package mydevpath

import grails.transaction.Transactional

 @Transactional
 class LoginService {
    static scope = "prototype"

     def firstMethod(){
        return 'From Service'
  }
}

On running and hitting the URL , I am facing below error.

NullPointerException occurred when processing request
: [POST] /login
Cannot invoke method firstMethod() on null object. Stacktrace follows:

java.lang.reflect.InvocationTargetException: null
        at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.
invoke(DefaultGrailsControllerClass.java:211)
        at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrai
lsControllerClass.java:188)

Can somebody help me with the Issue?

Regards, Pramod

Upvotes: 1

Views: 15744

Answers (1)

Mike W
Mike W

Reputation: 3932

Your service should be declared outside of the index action:

package mydevpath

import grails.rest.*
import grails.converters.*

class LoginController {
static responseFormats = ['json', 'xml']

def loginService

def index() {
    def val = loginService.firstMethod()

    render 'hello World' + val
}
}

Upvotes: 3

Related Questions