Grails:从服务init方法获取域对象

时间:2014-05-19 11:57:57

标签: grails groovy gorm

我已经创建了一个服务,在其init方法中它尝试从数据库加载一个对象,但是抛出了这个错误:

Caused by IllegalStateException: Method on class [pruebainitservice.Conf] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.
->>   15 | init      in pruebainitservice.ConfService
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|    262 | run       in java.util.concurrent.FutureTask
|   1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
|    615 | run       in java.util.concurrent.ThreadPoolExecutor$Worker
^    745 | run . . . in java.lang.Thread
| Error Forked Grails VM exited with error

我创建了一个示例项目,基本上就是这样做的;它只包含一个域类,一个服务,一个带有动作的控制器及其视图。您可以从这里下载https://github.com/okelet/grails-test-service-init

有谁知道为什么会这样?

Grails版本:2.3.8 Groovy版本:2.1.8 JVM:1.7.0_55供应商:Oracle Corporation操作系统:Linux

提前致意并表示感谢。

1 个答案:

答案 0 :(得分:0)

看起来像@PostConstruct注释正在使用它自己的ClassLoader,因此是例外。

我使用InitializingBean接口来执行您需要的初始化:

class SomeService implements InitializingBean {

  @Override
  void afterPropertiesSet() throws Exception {
    doStuffHere()
  }
}

更新:

我能找到的唯一解决方案是从BootStrap调用init-method:

class SomeService {

  void init(){
    log.debug("Cargando configuración...")
    def confs = Conf.findAll()
     // the rest
  }
}

class BootStrap {

  def confService

    def init = { servletContext ->
      confService.init()
    }
    def destroy = {
    }
}
相关问题