John Mercier
John Mercier

Reputation: 1705

Grails create a service from a factory

I would like to utilize a service written in Java in my Grails app using dependency injection. Creating it in Java without injection would look like this:

ServiceFactory.newInstance().getElementService()

I would like to use this in the same way services are injected for controllers, services, and jobs.

class ImportJob {
    def elementService
    ...
}

I know this should go into resources.groovy and this is what I have so far:

serviceFactory(ServiceFactory) { bean ->
    bean.factoryMethod = 'newInstance'
}

elementService(ElementService) {

}

I have found few resources in the documentation to help with this. How do I complete the elementService so it is creating the object as described above? Should I use a BeanBuilder?

Upvotes: 2

Views: 1548

Answers (2)

John Mercier
John Mercier

Reputation: 1705

Use bean.factoryMethod and bean.factoryBean in the elementService bean.

serviceFactory(ServiceFactory) { bean ->
    bean.factoryMethod = 'newInstance'
    bean.scope = 'singleton'
}

elementService(ElementService) { bean ->
    bean.factoryMethod = 'getElementService'
    bean.factoryBean = 'serviceFactory'
}

This is a simple solution especially if ServiceFactory is external and cannot be changed.

Upvotes: 1

Burt Beckwith
Burt Beckwith

Reputation: 75671

You could create a FactoryBean for this since it's not as direct as calling a method in a class:

package com.mycompany

import org.springframework.beans.factory.FactoryBean
import org.springframework.beans.factory.InitializingBean

class ElementServiceFactoryBean implements FactoryBean<ElementService>, InitializingBean {

   private ElementService elementService

   ElementService getObject() { elementService }

   Class<ElementService> getObjectType() { ElementService }

   boolean isSingleton() { true }

   void afterPropertiesSet() {
      elementService = ServiceFactory.newInstance().elementService
   }
}

and you'd register it in resources.groovy as

elementService(ElementServiceFactoryBean)

Upvotes: 5

Related Questions