【问题标题】:What is the best way, to use a Grails 3 Service in the Groovy Source folder?在 Groovy Source 文件夹中使用 Grails 3 服务的最佳方法是什么?
【发布时间】:2018-09-20 14:00:26
【问题描述】:

如问题所述,在 groovy 源中使用 grails 服务的最佳方式是什么?我目前正在使用此代码:

private RoleService roleService;

public RoleCommand() {
    this.roleService = (RoleService) Holders.getGrailsApplication().getMainContext().getBean("roleService");
}

有没有更好的方法来做到这一点?

编辑/解决方案: 我使用 Spring Dependency Injection 解决了它(使用 @Component 注释类并使用 Application.groovy 文件中的 @ComponentScan Annotation 注册包)

【问题讨论】:

  • 原因是什么? (因为我认为没有明显的理由这样做)
  • 在源中使用数据库中的数据
  • 听起来你想在单机模式下使用 GORM
  • 是和不是。我必须使用给定(Java)源和网络应用程序中的数据。源代码中有一个用于运行即时通讯程序的机器人。机器人通过 grails 服务消费和发布数据到 GORM。这是一种不好的做法吗?
  • 如果我是你,我会为机器人创建一个(微)服务,它应该与主应用程序没有太大关系。在该服务中,我会单独使用 GORM

标签: grails groovy dependency-injection grails-3.3


【解决方案1】:

你的代码可能更时髦:

import grails.util.Holders

class RoleCommand {

    // getter for the service
    def getRoleService() {
        Holders.grailsApplication.mainContext.getBean 'roleService' 
        // or Holders.applicationContext.getBean 'roleService'
    }

    def useTheService() {
       // use the getter method
       def something = roleService.doSomething()
    }

}

【讨论】:

    【解决方案2】:

    说实话,我会避免这样做。

    我一直在开发一个包含各种服务和命令类的大型 Grails 应用程序。

    这是我一开始就想犯的错误之一,但随着我的发展,我意识到没有必要这样做。

    命令对象的作用应该是将参数包装在请求中,以便您在应用程序的控制器端轻松访问和验证命令。

    如果一切正常,您应该调用所需的服务方法来创建对请求的响应。

    【讨论】:

    • “Command”这个名字在我的上下文中具有误导性。我使用类的名称,因为它是一个命令,可以由机器人触发。这实际上不是命令模式。
    猜你喜欢
    • 2011-06-08
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多