Frage

Writing a small web-app in Grails I encountered a problem with global objects. I have a class which runs threads - ExecutorService with queuing.

The problem is where to create an object of this class, to have it available in Controller?

I've tried at init (BootStrap) but there's no chance then of getting its instance anywhere else.

In general - what I need is an object in one single instance for whole application, with access from Model and/or Controller.

War es hilfreich?

Lösung

In general - what I need is an object in one single instance for whole application, with access from Model and/or Controller.

The standard way to achieve this is to declare the object as a Spring bean in grails-app/conf/spring/resources.groovy

threadPool(java.util.concurrent.Executors) { bean ->
  bean.factoryMethod = "newCachedThreadPool"
}

Then in controllers/services/etc. you can inject this bean the same as you would with grails services, i.e.

def threadPool

But in this case you may find it easier simply to use the executor plugin, which defines such a bean for you and handles the intricacies of ensuring there is a valid GORM session available to the background tasks.

Andere Tipps

Why not wrap your Executorservice inside a Spring Bean, or using something like:

grailsApplication.controllerClasses.each {controller ->
controller.metaClass.executorService = { ->
      executorService
 }
}

Actually I have come to something before checking answers.

For a given domain class (Example) and controller (ExampleController) create

 ExampleService

and simply include all the needed things there. Set behaviour to @Singleton (default). Then in Controller inject the instance as follows:

 def exampleService
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top