【问题标题】:Grails Data Service Cannot Use Regular ServiceGrails 数据服务无法使用常规服务
【发布时间】:2020-10-30 06:23:28
【问题描述】:

又一个新冠病毒日快乐。当我使用 generate-all 时,Grails 会为我创建数据服务。我开始了解什么是数据服务。

我也有自己的服务供我的 Author 和 Book 类使用。我将我的服务命名为 ImportService。在数据服务将我的书籍保存到数据库之前,我在 ImportService 中有一些方法可以清理从 CSV 文件中读取的书籍数据。我还按照说明使数据服务成为抽象类。因此,我可以将自己的方法放入数据服务中。

由于 Author 有自己的 AuthorService,而 Book 也有自己的 BookService,我希望不同的 Data Service 访问我 ImportService 中的方法。因此,我不必多次复制和粘贴导入 CSV 代码。因此,我将 ImportService importService 行放在 AuthorServie 类和 BookService 类中。这并不顺利。 importService 在数据服务类中始终为 NULL。我谷歌这个问题。他们说我不能向 grails.gorm.services.Service 注入其他服务。

有一个帖子说要做一个豆子。我是 Grails 的新手。即使发布了代码,我也不知道他们在说什么。我的部分背景是汇编语言、C 和 Pascal。我的脑海里充满了诸如自上而下、子程序、库、地址和指针之类的术语。我不知道 Bean 是什么。

就是这样。我想知道这是一个错误还是设计使您无法向 gorm 服务注入服务。

感谢您的“指点”。

【问题讨论】:

  • 您没有说明您使用的是什么版本的 Grails 或什么版本的 GORM,所以我不知道这是否相关,但我们最近修复了 GORM 中的一个相关错误。见github.com/grails/gorm-hibernate5/issues/202
  • 我正在使用 Grails 4.0.3。我是 Grails 的新手。我不知道在哪里可以找到 GORM 版本。你能告诉我在哪里可以获得 GORM 版本吗?谢谢!我使用的是 Grails 4.0.4,但它一直在崩溃。有人建议回滚到 4.0.3。这就是我使用 4.0.3 的原因。
  • “请告诉我在哪里可以获得 GORM 版本?” - 如果不查看您的构建很难说,但在 Grails 4.0.3 中默认指定 GORM 版本的位置将在项目顶部的 gradle.properties 文件中。
  • 谢谢。这是版本号。这是否导致我无法在数据服务中使用服务的问题? grailsVersion=4.0.3 gorm.version=7.0.6.RELEASE
  • 我相信修复在 7.0.7.RELEASE 中。

标签: grails


【解决方案1】:

https://github.com/jeffbrown/tom6502servicedi 上查看该项目。该项目使用 Grails 4.0.3 和 GORM 7.0.7。

https://github.com/jeffbrown/tom6502servicedi/blob/main/grails-app/services/tom6502servicedi/ImportService.groovy

package tom6502servicedi

class ImportService {

    int getSomeNumber() {
        42
    }
}

https://github.com/jeffbrown/tom6502servicedi/blob/917c51ee173e7bb6844ca7d40ced5afbb8d9063f/grails-app/services/tom6502servicedi/AuthorService.groovy

package tom6502servicedi

import grails.gorm.services.Service
import org.springframework.beans.factory.annotation.Autowired

@Service(Author)
abstract class AuthorService {

    @Autowired
    ImportService importService

    // ...

    int getSomeNumberFromImportService() {
        importService.someNumber
    }
}

https://github.com/jeffbrown/tom6502servicedi/blob/917c51ee173e7bb6844ca7d40ced5afbb8d9063f/grails-app/controllers/tom6502servicedi/AuthorController.groovy

package tom6502servicedi

import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*

class AuthorController {

    AuthorService authorService

    // ...

    def someNumber() {
        render "The Number Is ${authorService.someNumberFromImportService}"
    }
}

someNumber 操作发送请求将验证ImportService 是否已注入AuthorServiceAuthorService 是否已注入AuthorController

$ curl http://localhost:8080/author/someNumber
The Number Is 42

【讨论】:

  • 哇!这是奇迹!完全违背物理定律!!!在数据服务中添加 import org.springframework.beans.factory.annotation.Autowired 和单词 @Autowired 使 Grails 现在可以获取对我的 ImportService 类的引用。 T-H-A-N-K-S!!!
猜你喜欢
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多