2011-02-11 28 views
32

我創建一個Grails服務,將通過一個Java庫第三方REST API進行交互。 Java庫需要通過url,用戶名和密碼來獲取REST API的憑證。進樣Grails應用程序配置到服務

我想存儲在configuration/Config.groovy這些憑據,將它們提供給服務,並確保證書可向服務它需要他們。

我明白grailsApplication.config是提供給控制器和通過相關的配置值可以被提供給該服務的服務的方法,例如這樣的:

package example 

class ExampleController { 

    def exampleService 

    def index = { } 

    def process = { 
     exampleService.setCredentials(grailsApplication.config.apiCredentials) 
     exampleService.relevantMethod() 
    } 
} 


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(); 
    } 
} 

我覺得這種方法略有瑕疵,因爲它取決於控制器呼籲setCredentials()上。擁有自動提供給服務的證書將更加健壯。

(使用Grails我目前不熟悉不夠)或者是這兩種選擇可行的:

  1. 進樣grailsApplication.config.apiCredentials到控制器中的服務創建服務時?

  2. 提供某種形式的允許憑據中傳遞給在實例化時該服務的服務構造器呢?

將憑據注入到服務中是理想的。這怎麼能做到?

+1

仍然會很好,如果有一些方法注入實際的配置屬性,而不是整個grailsApplication對象。 – 2012-05-16 02:30:09

回答

73

grailsApplication對象是服務中提供,允許這樣的:

package example 

import com.example.ExampleApiClient; 

class ExampleService { 

    def grailsApplication 

    def relevantMethod() { 

     def client = new ExampleApiClient(
      grailsApplication.config.apiCredentials.baseUrl 
      grailsApplication.config.apiCredentials.username, 
      grailsApplication.config.apiCredentials.password 
     ) 

     return client.action(); 
    } 
} 
+10

請注意,我發現您需要在方法中使用grailsApplication.config。[...]。否則,如果嘗試從方法外的配置文件中提取數據,則會看到空指針。 – arcdegree 2013-02-05 00:25:29

3

對於上下文,你不能注入grailsApplication豆(服務是完全一致的,由喬恩·克拉姆描述),例如放在src/Groovy中的一個輔助類,你可以使用持有人類訪問:

def MyController { 
    def myAction() { 
     render grailsApplication == grails.util.Holders.grailsApplication 
    } 
} 
10

即使grailsApplication可以在服務注入,我覺得服務壽不需要處理配置,因爲測試和打破Single Responsibility principle更困難。另一方面,Spring可以更強大的方式處理配置和實例化。 Grails在其文檔中有a dedicated section

使用Spring讓你的榜樣的工作,你應該在resources.groovy

// Resources.groovy 
import com.example.ExampleApiClient 

beans { 
    // Defines your bean, with constructor params 
    exampleApiClient ExampleApiClient, 'baseUrl', 'username', 'password' 
} 

註冊服務作爲一個bean然後,你將能夠注入的依賴到你的服務

class ExampleService { 
    def exampleApiClient 

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

另外,在您的Config.groovy文件中,您可以使用Grails約定優先於配置語法覆蓋任何Bean屬性:beans.<beanName>.<property>

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

Config.groovyresources.groovy都支持不同的環境配置。

相關問題