从服务到控制器的Grails依赖注入不起作用

时间:2017-09-08 14:14:07

标签: grails grails-controller

根据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

上面创建了以下目录结构 enter image description here

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

使用邮递员索取 enter image description here

我是grails的新手,请帮我弄清楚出了什么问题,可能是我错过了什么。

2 个答案:

答案 0 :(得分:1)

错误消息表明您指的是不存在的属性。而不是render kpiReportService.serviceMethod,而是render kpiReportService.serviceMethod()

答案 1 :(得分:0)

服务作为类变量注入

class KpiReportController {
    def kpiReportService

    def index() {
        render kpiReportService.serviceMethod()
        //render "Hello from KpiReportController"
    }
}