【问题标题】:Grails: Fetch domain object from service init methodGrails:从服务初始化方法获取域对象
【发布时间】:2014-05-19 11:57:56
【问题描述】:

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

提前致谢。

【问题讨论】:

    标签: grails groovy grails-orm


    【解决方案1】:

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

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

    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 = {
        }
    }
    

    【讨论】:

    • 不幸的是,这不起作用。它抛出相同的异常。
    • 您是否删除了注释?
    • 你为什么要在你的服务中注入Conf conf?删除它
    • 它不是(或至少不应该)注入的,而是服务的一个实例变量。不能这样做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 2014-05-20
    相关资源
    最近更新 更多