1

I've read various posts such as:

link1 link2

but none of them worked for me.

Here's my current (broken) resources.groovy file:

beans = {

    def instance = Class.forName(grailsApplication.config.foo.bar)
    exampleService(instance)
}

the value of foo.bar in the property file is the name of a class (that implements ExampleService).

Can it be done?

Community
  • 1
  • 1
FinalFive
  • 1,465
  • 2
  • 18
  • 33
  • I had the same concern and this page helped me: http://blog.lidalia.org.uk/2010/06/injecting-bean-into-grails-controller.html – JLBarros Apr 10 '12 at 17:40

1 Answers1

0

On a previous project we used different classes for the beans depending on an environment variable. There we start with the service interface to find the implementation class we want to use based on a naming convention, as shown in the code snippet below.

The only difference with your code is that we use the classloader of the service interface to retrieve the implementation class. Another option is ofcourse that grailsApplication.config.foo.bar does not contain a correct value.

In the grails-app/conf/spring directory our beans file contained the following code to load the correct implementation class:

beans = {
    addressService(getImplementation(AddressService))
    appointmentService(getImplementation(AppointmentService))
}

def getImplementation(Class service) {
    if (CH.config.mockAllServices == 'true' || CH.config."mock${service.simpleName}" == 'true') {
        return service.classLoader.loadClass(service.name + 'Mock')
    }
    return service.classLoader.loadClass(service.name + 'Impl')
}
Ruben
  • 9,056
  • 6
  • 34
  • 44