在 Grails 中编写一个小型网络应用程序时,我遇到了全局对象的问题。我有一个运行线程的类 - 带队列的 ExecutorService。
问题是在哪里创建这个类的对象,让它在 Controller 中可用?
我已经在 init (BootStrap) 处尝试过,但是没有机会在其他任何地方获取它的实例。
一般来说——我需要的是整个应用程序的单个实例中的一个对象,可以从模型和/或 Controller 访问。
最佳答案
In general - what I need is an object in one single instance for whole application, with access from Model and/or Controller.
实现此目的的标准方法是 declare the object as a Spring bean在 grails-app/conf/spring/resources.groovy
threadPool(java.util.concurrent.Executors) { bean ->
bean.factoryMethod = "newCachedThreadPool"
}
然后在 Controller /服务/等等。您可以像使用 grails 服务一样注入(inject)这个 bean,即
def threadPool
但在这种情况下,您可能会发现使用 the executor
plugin 更容易,它为您定义了这样一个 bean,并处理确保有一个有效的 GORM session 可用于后台任务的复杂问题。
关于java - Grails 中的全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592717/