Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate interface from implementation in Grails services?

I was wondering if it's possible to create a service interface on Grails and I can't find a proper way of doing it. This explanation isn't satisfactory, since it seems to mix Java and Groovy:

http://www.grails.org/doc/latest/guide/8.%20The%20Service%20Layer.html

It seems to me like a bad design flaw of the framework, given that the interface mechanism is one of the best features of Java (and most OO languages).

Any idea to clarify this issue?

Thanks! Mulone

like image 597
Mulone Avatar asked Feb 02 '11 10:02

Mulone


1 Answers

You can have an interface, but actually you don't need one. If I understand you correctly you would like to have two implementations of a service and be able to choose which one to use.

Simply implement two services named for example MyService1 and MyService2, then in grails-app/conf/spring/resource.groovy you can specify:

beans = {
    ... 
    // syntax is beanId(implementingClassName) { properties }
    myService(MyService1)
    ...
}

or even:

beans = {
    ...
    if (someConfigurationOption) {
        myService(MyService1)
    } else {
        myService(MyService2)
    }
}

This is how you tell Spring which service to actually inject for myService. Now you will be able to use myService like:

public MyController {
    def myService
    ...
}

and Spring will auto wire a proper implementation. This allows you to configure which service implementation to use based for example on some configuration.

like image 88
Marcin Niebudek Avatar answered Nov 08 '22 09:11

Marcin Niebudek