"Cannot invoke method on null object" 将服务注入控制器时
"Cannot invoke method on null object" when injecting service into a controller
我创建了一个全新的 Grails 4.0.0 应用程序并使用 grails cmd 创建了一个域/控制器。我还创建了一个简单的服务,该服务 returns "Hello World" 到控制器,然后将其呈现到屏幕上。但是,我在尝试调用服务方法时得到 "Cannot invoke method on null object" - 似乎依赖注入无法正常工作。
我尝试过使用 "def" 声明服务,我也尝试过使用 class 名称声明 - 两者似乎都不起作用。
package uk.org.pmms
import grails.gorm.transactions.Transactional
@Transactional
class HelloWorldService {
def hello() {
return "Hello World"
}
}
package uk.org.pmms
class ClientController {
//static scaffold = Client
def helloWorld
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorld.hello())
}
}
我希望控制器 return 显示在 GSP 页面上的 clientInstance 数据和字符串 "Hello World"。
当我删除响应语句的 "message:" 部分时,它会正确显示客户端信息,因此问题肯定出在服务调用上。
为您的服务创建的 bean 的名称将是 helloWorldService
class ClientController {
def helloWorldService // <--- corrected bean name for auto wire by name.
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorldService.hello())
}
}
我创建了一个全新的 Grails 4.0.0 应用程序并使用 grails cmd 创建了一个域/控制器。我还创建了一个简单的服务,该服务 returns "Hello World" 到控制器,然后将其呈现到屏幕上。但是,我在尝试调用服务方法时得到 "Cannot invoke method on null object" - 似乎依赖注入无法正常工作。
我尝试过使用 "def" 声明服务,我也尝试过使用 class 名称声明 - 两者似乎都不起作用。
package uk.org.pmms
import grails.gorm.transactions.Transactional
@Transactional
class HelloWorldService {
def hello() {
return "Hello World"
}
}
package uk.org.pmms
class ClientController {
//static scaffold = Client
def helloWorld
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorld.hello())
}
}
我希望控制器 return 显示在 GSP 页面上的 clientInstance 数据和字符串 "Hello World"。
当我删除响应语句的 "message:" 部分时,它会正确显示客户端信息,因此问题肯定出在服务调用上。
为您的服务创建的 bean 的名称将是 helloWorldService
class ClientController {
def helloWorldService // <--- corrected bean name for auto wire by name.
def show(Long id){
Client clientInstance = Client.get(id)
respond ("client": clientInstance, "message": helloWorldService.hello())
}
}