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