【问题标题】:Why don't Domain class static methods work from inside a grails "service"?为什么域类静态方法不能从 grails“服务”内部工作?
【发布时间】:2011-01-31 22:29:51
【问题描述】:

我希望 grails 服务能够访问域静态方法、查询等。

例如,在控制器中,我可以调用

IncomingCall.count()

获取“IncomingCall”表中的记录数

但如果我尝试从服务内部执行此操作,则会收到错误消息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'incomingStatusService': Invocation of init method failed; nested exception is groovy.lang.MissingMethodException: No signature of method: static ms.wdw.tropocontrol.IncomingCall.count() is applicable for argument types: () values: []

这些方法是如何被注入的?在控制器中似乎没有神奇的 def 语句可以做到这一点。还是我的 Service 类中没有 Hibernate 的问题?

我也试过这样:

import ms.wdw.tropocontrol.IncomingCall
import org.codehaus.groovy.grails.commons.ApplicationHolder

// ...

void afterPropertiesSet() {

    def count = ApplicationHolder.application.getClassForName("IncomingCall").count()
    print "Count is " + count
}

它失败了。 ApplicationHolder.application.getClassForName("IncomingCall") 返回 null。这么称呼是不是太早了?有没有可以调用的“后期初始化”?我以为这就是“afterPropertiesSet()”的目的……

【问题讨论】:

  • 您是否尝试将包含 IncomingCall 域的包包含到您的服务源中?
  • 是的。我有一个导入声明。

标签: hibernate grails groovy dns


【解决方案1】:

元类方法是在配置 Spring 应用程序上下文后连接起来的,因此尝试在 afterPropertiesSet 中调用它们会失败。相反,您可以创建一个常规的 init() 方法并从 BootStrap 调用它:

import ms.wdw.tropocontrol.IncomingCall

class FooService {

   void init() {
      int count = IncomingCall.count()
      println "Count is " + count
   }
}

然后用这个来称呼它:

class BootStrap {

   def fooService

   def init = { servletContext ->
      fooService.init()
   }
}

【讨论】:

  • 非常感谢!我很高兴我问了,因为我从没想过要在 Bootstrap 类中添加一些东西....
  • 这行得通。我从“init”方法启动一个工作线程,我可以从中访问我的 Domain 类动态方法....
【解决方案2】:

我发现,真正的答案是不要这样做。

我应该将我的服务注入我的域类并从那里调用它。

我可以使用“触发”方法,如 afterInsert 来根据需要调用我的服务方法

class Deal {
    def authenticateService

    def afterInsert() {
        def user = authenticateService.userDomain();
        ....
    }
....
}

(例如,来自 grails 服务文档)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 2018-09-20
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2015-10-07
    • 1970-01-01
    相关资源
    最近更新 更多