grails - 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中添加代码以将服务分配给服务中所谓的注入属性。[不寒而栗]
解决方案
我试图重现相同的-
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
}
}
它打印-
推荐阅读
- c++ - reinterpret_cast - 任何整数或枚举类型的值都可以转换为指针类型
- javascript - 开玩笑 - 如果存在 prop,则测试是否调用函数
- xml - 有没有一种简单的方法来初始化 XML 文件中的变量?
- python - 在python中交替时间定期安排任务
- flutter - 我如何在 Flutter 中制作这样的动画
- c# - 为什么我的 WebClient 无法读取失败的 API 调用?
- javascript - ReactJS setInterval 不会在 Safari 中重新渲染
- string - PowerShell:如何在一行文本中找到一个单词并修改其背后的数据
- reactjs - 如何在 Typescript 中使用 react-router-dom 从路由渲染组件访问 routeProps(历史、匹配、位置)?
- c# - 缺少 LogonHostedExchangeMailbox 方法