How to separate interface from implementation in Grails services?

前端 未结 4 1880
鱼传尺愫
鱼传尺愫 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 06:14

    The best solution I found for this is using Spring bean aliases. Basically you need to:

    1) Create an interface in src/groovy ( MyService.groovy )

    2) Inject your service wherever you need it:

    class MyController {
        MyService myService
    }
    

    3) Create your regular services implementing that interface ( ImplOneService.groovy, ImplTwoService.groovy )

    4) Add an entry to resources.groovy where you define which implementation to use (eventually, testing for environment, or anything else you need):

    beans = {
        if (...development, useFTP, etc...) {
            springConfig.addAlias 'myService', 'ImplOneService'
        } else {
            springConfig.addAlias 'myService', 'ImplTwoService'
        }
    }
    

    Complete sources here

    My comments: Using interfaces in groovy really seems like some kind of "I want to stick with some java stuff I'm more comfortable with". In this case, strong-typing. But it's exactly the nice part of groovy saying "No worries, you can keep the java way if you want".

提交回复
热议问题