首页 > 解决方案 > Grails 4 服务没有被注入到 Grails 数据服务中

问题描述

这是关于注入数据服务的 Grails 服务。问题是注入的服务在运行时为空。这是一个例子。

class MessagingService {

    def sendEmail(String message) {
      ...
    }
}
interface IFlowService {
    ...
}

@Service(Flow)
abstract class FlowService implements IFlowService {

    MessagingService messagingService

    void sendFoo() {
        messagingService.sendEmail(message)
    }
}

FlowService并且MessagingService都位于grails-app/services.

FlowService调用时sendEmail有一个 NPE,因为messagingService为空。

MessagingService是手写的,与域无关。

本项目使用 Grails 4.0.10,问题出现多次。当通常的 Gails 魔法(即注射)不起作用时,我用 kludges 解决了前一两个问题,你知道,只是为了避免卡住。

现在在我看来,这个问题是可以预见的,每次我编写与域无关的服务时都会发生这种情况。我错过了文档中的某些内容吗?处理此问题的适当方法是什么?

Kludge:为了解决这个问题,我sayHi在有问题的服务中包含了一个方法。它只记录一条调试消息。sayHi我从BootStrap调用以检查它是否有效。确实如此,令人惊讶。然后我在BootStrap中添加代码以将服务分配给服务中所谓的注入属性。[不寒而栗]

标签: grailsgrails-4

解决方案


我试图重现相同的-

interface IFlowService {

}
@Service(Flow)
abstract class FlowService implements IFlowService {

    MessagingService messagingService

    void hello() {
        println "hello"
        messagingService.hi()      // <- NPE
    }
}
class MessagingService {

    void hi() {
        println "hi"
    }
}

这似乎是 Grails 中的一个错误。但是您只需添加@Autowired服务即可轻松解决此问题(可能是一种解决方法)-

import org.springframework.beans.factory.annotation.Autowired

@Service(Flow)
abstract class FlowService implements IFlowService {

    @Autowired
    MessagingService messagingService

    void hello() {
        println "hello"
        messagingService.hi()      // <- No NPE
    }
}

它打印-

在此处输入图像描述


推荐阅读