2014-06-27 44 views
0

我對groovy/grails的初始化有個疑問。當我有以下類時,sInstance不會傳入SService初始化。Grails類的初始化

class SService { 

    String sInstance 
    String app 

public getSInstance{ 
    return sInstance 
    } 
} 

此返回null,其中

class A { 

    String sInstance 
    String app 
    String dbInstance 

public initializeSService{ 
    SService s = new SService(sInstance:sInstance, app:app) 
    } 
} 

從SService類返回sInstance變量:

class A { 

    String sInstance 
    String app 
    String dbInstance 

    SService s = new SService(sInstance:sInstance, app:app) 
} 

SService類。

爲什麼會這樣以及如何讓SService對象用類A的構造函數初始化?

回答

2

你不能做這樣的事情:

class A { 

    String sInstance 
    String app 
    String dbInstance 

    SService s = new SService(sInstance:sInstance, app:app) 
} 

與問題是,當你創建SService的一個實例,sInstance尚未初始化。如果要將sInstance傳遞給A類中的某個其他類的構造函數,則必須在sInstance被賦予一個值之後執行此操作,例如在完全構造A之後調用的方法。

編輯:

試圖澄清從下面的評論的內容:

class A { 
    String sInstance 
    String app 
    String dbInstance 

    void anyMethod() { 
     // this will work as long as you have initialized sInstance 
     SService s = new SService(sInstance:sInstance, app:app) 
    } 
} 

取決於你真正要做的,或許真的在這個方向:

class A { 
    String sInstance 
    String app 
    String dbInstance 
    SService s 

    void initializeS() { 
     if(s == null) { 
      // this will work as long as you have initialized sInstance 
      s = new SService(sInstance:sInstance, app:app) 
     } 
    } 
} 

或者:

class A { 
    String sInstance 
    String app 
    String dbInstance 
    SService theService 

    SService getTheService() { 
     if(theService == null) { 
      // this will work as long as you have initialized sInstance 
      theService = new SService(sInstance:sInstance, app:app) 
     } 
     theService 
    } 

    def someMethodWhichUsesTheService() { 
     getTheService().doSomethingToIt() 
    } 
} 
+0

如果我使用另一種方法(在A完全構建之後),那麼我無法將其作爲類變量進行訪問。我怎樣才能構造它作爲一個類變量? –

+0

爲什麼你不能在方法中訪問它?在A中定義的任何方法都可以訪問'A'中定義的所有字段和屬性。 –

+0

如果我執行「def startService()」並將SService的初始化調用放在那裏,那麼在另一種方法中,我無法訪問我創建的服務。我收到以下錯誤消息沒有此類屬性:s –