Grails:从服务初始化方法获取域对象

标签 grails groovy grails-orm

我创建了一个服务,它在它的 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

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

有谁知道为什么会这样?

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

提前致以问候和感谢。

最佳答案

看起来像 @PostConstruct注释正在使用它自己的 ClassLoader ,因此异常(exception)。

我会使用 InitializingBean接口(interface)来做你需要的初始化:

class SomeService implements InitializingBean {

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

更新:

我能找到的唯一解决方案是从 BootStrap 调用初始化方法:
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 = {
    }
}

关于Grails:从服务初始化方法获取域对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23737144/

相关文章:

grails - 如何提高grails中保存批量数据的性能?

grails - Grail数据迁移插件

grails - 如果子字符串匹配,则在“字符串”字段中插入链接

gradle - gradle 'from'不移动文件

grails - Grails 中已弃用 install-plugin 命令

hibernate - Grails/GORM : org. hibernate.AssertionFailure: xyz 中的 null id(发生异常后不刷新 session )

grails - 带数据的POST请求

spring - ref() 没有在 grails 上使用 spring dsl 获取嵌套映射值的 bean 配置

java - Java 风格的 Groovy 和 Java 一样快吗?

grails - 如何将对象实例从一个 Controller 传递到grails中的另一个 Controller 中的 Action