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

Grails dependency injection from service to controller is not working

根据 grails 3.1.13 guide 我正在尝试向我的控制器添加服务依赖性,但不知何故它对我不起作用。它正在为 Cannot get property 'serviceMethod' on null object. 抛出 NullPointerException 下面我提到重现的步骤。

执行以下命令

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 的新手,请帮我找出问题所在,可能是我遗漏了什么。

服务作为 class 变量注入

class KpiReportController {
    def kpiReportService

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

错误消息表明您指的是一个不存在的 属性。而不是 render kpiReportService.serviceMethod 你想要 render kpiReportService.serviceMethod().