根据grails 3.1.13 guide我试图将服务依赖项添加到我的控制器,但不知怎的,它对我不起作用。正在向NullPointerException
投掷Cannot get property 'serviceMethod' on null object.
下面我提到了重现的步骤。
执行以下命令
grails create-app DepInjectionTest
grails create-controller com.abc.project.KpiReport
grails create-service com.abc.project.KpiReport
KpiReportService
@Transactional
class KpiReportService {
def serviceMethod() {
return "Hello from KpiReportService"
}
}
KpiReportController
class KpiReportController {
def index() {
def kpiReportService
render kpiReportService.serviceMethod
//render "Hello from KpiReportController"
}
}
异常
Grails application running at http://localhost:8080 in environment: development
ERROR org.grails.web.errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [POST] /KpiReport/index
Cannot get property 'serviceMethod' on null object. Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:210)
at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:187)
at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException: Cannot get property 'serviceMethod' on null object
at com.abc.project.KpiReportController.index(KpiReportController.groovy:7)
... 13 common frames omitted
我是grails的新手,请帮我弄清楚出了什么问题,可能是我错过了什么。
答案 0 :(得分:1)
错误消息表明您指的是不存在的属性。而不是render kpiReportService.serviceMethod
,而是render kpiReportService.serviceMethod()
。
答案 1 :(得分:0)
服务作为类变量注入
class KpiReportController {
def kpiReportService
def index() {
render kpiReportService.serviceMethod()
//render "Hello from KpiReportController"
}
}