0

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

private RoleService roleService;

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

有一个更好的方法吗?

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

4

2 回答 2

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()
    }

}
于 2018-09-24T09:43:13.593 回答
0

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

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

这是我一开始就想犯的错误之一,但随着我的发展,我意识到在任何情况下都不需要这样做。

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

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

于 2018-09-20T14:38:02.877 回答