title: Inject grails application configuration into service
body: <p>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, username and password.</p>
  
  <p>I'd like to store these credentials in <code>configuration/Config.groovy</code>, make them available to a service and ensure that credentials are available to the service before it requires them.</p>
  
  <p>I appreciate that <code>grailsApplication.config</code> is available to controllers and that through a method of a service the relevant config values can be provided to the service, such as this:</p>
  
  <pre><code>package example
  
  class ExampleController {
  
      def exampleService
  
      def index = { }
  
      def process = {
          exampleService.setCredentials(grailsApplication.config.apiCredentials)
          exampleService.relevantMethod()
      }
  }
  </code></pre>
  
  <p><br></p>
  
  <pre><code>package example
  
  import com.example.ExampleApiClient;
  
  class ExampleService {
  
      def credentials
  
      def setCredentials(credentials) {
          this.credentials = credentials
      }
  
      def relevantMethod() {
  
          def client = new ExampleApiClient(
              credentials.baseUrl,
              credentials.username,
              credentials.password
          )
  
          return client.action();
      }
  }
  </code></pre>
  
  <p>I feel this approach is slightly flawed as it depends on a controller calling <code>setCredentials()</code>. Having the credentials made available to the service automagically would be more robust.</p>
  
  <p>Is either of these two options viable (I currently not familiar enough with grails):</p>
  
  <ol>
  <li><p>Inject <code>grailsApplication.config.apiCredentials</code> into the service in the controller when the service is created?</p></li>
  <li><p>Provide some form of contructor on the service that allows the credentials to be passed in to the service at instantiation time?</p></li>
  </ol>
  
  <p>Having the credentials injected into the service is ideal. How could this be done?</p>