我創建一個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我目前不熟悉不夠)或者是這兩種選擇可行的:
進樣
grailsApplication.config.apiCredentials
到控制器中的服務創建服務時?提供某種形式的允許憑據中傳遞給在實例化時該服務的服務構造器呢?
將憑據注入到服務中是理想的。這怎麼能做到?
仍然會很好,如果有一些方法注入實際的配置屬性,而不是整個grailsApplication對象。 – 2012-05-16 02:30:09