How to separate interface from implementation in Grails services?

前端 未结 4 1879
鱼传尺愫
鱼传尺愫 2021-02-04 05:15

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

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 05:57

    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.

提交回复
热议问题