如果相同的業務邏輯適用於這兩個帳戶,但考慮到你不能有一個單一的服務類說話的兩個帳戶的API,然後是你可以有2個服務類(這只不過是2個不同的春天bean)與默認單例作用域。
class Account1Service{
}
class Account2Service{
}
我也會嘗試如果我可以在這裏使用繼承在這種情況下,如果我有共同的邏輯,可以共享。但請記住,如果你是從一個抽象類,然後抽象類必須放置在src/groovy
就是外面/grails-app/
違抗依賴注入繼承服務類。在這種情況下,你可能最終得到(未經測試,但你能不能堅持DRY概念)
// src/groovy
abstract class BrokerageService {
def populateAccountDetails(Long accountId)
def checkAccountStatus(Long accountId)
}
//grails-app/services
class Account1Service extends BrokerageService {
//Implement methods + add logic particular to Account1
//By default transacitonal
}
class Account2Service extends BrokerageService {
//Implement methods + add logic particular to Account2
//By default transacitonal
}
也保持了一份說明,範圍singleton
,你會格外小心(最好避免)保持在全球範圍的性質服務類。儘量使無國籍儘可能。除非另有情況或業務邏輯的要求使用服務水平範圍像session
,flow
或request
,我會一直堅持到默認singleton
範圍。
要回答你的第二個問題,你不需要任何實例使用Grails服務類的。當使用適當的命名法時,容器會注入適當的服務類(使用Spring IoC)。
//camelCase lower initial
def account1Service
def account2Service
UPDATE
這是爲了應對所提供的附加信息:在上面的例子中,服務類將自動如果你在那裏你婉TTO使用的服務按照類命名約定注入OP。
參照上述場景,在默認的singleton
範圍內只能有一個service
類來處理事情。最好的部分是,由於您要離開您的網絡,並且不擔心自己的數據庫事務,因此服務類可以設置爲非事務性。但這又取決於情況需要。以下是服務類的外觀。
//grails-app/service
class BrokerageService{
//Service method to be called from controller or any endpoint
def callServiceMethod(Long accountId){
.......
doSomethingCommonToAllAccounts()
.........
def _ibConfig = [:] << lookupIBGatewayConfigForAccount(accountId)
........
//Configure an IB Gateway according to the credentials
//Call IB Gateway for Account using data got from _ibConfig map
//Call goes here
}
def doSomethingCommonToAllAccounts(){
........
........
}
def lookupIBGatewayConfigForAccount(accountId){
def configMap = [:]
//Here lookup the required IP, account credentials for the provided account
//If required lookup from database, if you think the list of accounts would grow
//For example, if account is JPMorgan, get credentials related to JPMorgan
//put everything in map
configMap << [ip: "xxx.xx.xx.xxx", port: 80, userName: "Dummy"] //etc
return configMap
}
}
服務類的範圍是單這意味着有將只有一個堆中類,這也意味着,任何類級別屬性(比其他方法)將是有狀態的實例。在這種情況下,你只處理將是無狀態的方法,並且足以達到目的。每次交易發生時,您都可以獲得所需的東西,而無需花費堆積或創建新的BrokerageService
實例。
每筆交易(包括一個賬戶)最終都會調用服務,從數據庫(或配置屬性或平面文件或屬性文件)查找憑證,然後配置IB網關並呼叫/通話給網關。
當你說服務,你的意思是Grails服務?爲什麼你覺得這是最好的方式爲每個帳戶創建服務類的新實例,而不是使用默認的'singleton'範圍? – dmahapatro
是的,Grails服務。我不確定你是什麼意思。我期望每個服務是一個單身人士,運行相同的代碼,但與包含帳號的實例字段。您是否建議同一個單獨服務處理這兩個帳戶的訂單?如果是這樣,由於API的設計方式,這實際上不起作用。我需要爲每個帳戶提供專門的服務。 – greymatter
關於可用服務範圍的更多詳細信息,請參閱Elias訪問[本頁](http://grails.org/doc/2.2.1/guide/services.html#scopedServices)所述的答案。 – dmahapatro