Inject grails application configuration into service

前端 未结 3 1620
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 15:23

I\'m creating a grails service that will interact with a 3rd party REST API via a Java library. The Java library requires credentials for the REST API by means of a url, use

3条回答
  •  臣服心动
    2020-12-15 16:23

    Even though grailsApplication can be injected in services, I think services should not have to deal with configuration because it's harder to test and breaks the Single Responsibility principle. Spring, on the other side, can handle configuration and instantiation in a more robust way. Grails have a dedicated section in its docs.

    To make your example work using Spring, you should register your service as a bean in resources.groovy

    // Resources.groovy
    import com.example.ExampleApiClient
    
    beans {
        // Defines your bean, with constructor params
        exampleApiClient ExampleApiClient, 'baseUrl', 'username', 'password'
    }
    

    Then you will be able to inject the dependency into your service

    class ExampleService {
        def exampleApiClient
    
        def relevantMethod(){
            exampleApiClient.action()
        }
    }
    

    In addition, in your Config.groovyfile, you can override any bean property using the Grails convention over configuration syntax: beans..:

    // Config.groovy
    ...
    beans.exampleApiClient.baseUrl = 'http://example.org'
    

    Both Config.groovy and resources.groovy supports different environment configuration.

提交回复
热议问题