2016-11-18 34 views
0

我有以下播放辛格爾頓:訪問播放辛格爾頓方法

package p1 

@Singleton 
class MySingleton @Inject() (system: ActorSystem, properties: Properties) { 

    def someMethod = { 
     // ........ 
    } 
} 

當我嘗試從類訪問方法someMethod(),甚至當我導入包,我得到一個編譯錯誤說,該方法是未找到。如何解決這個問題?

+0

你能證明你是如何注射和使用'MySingleton'和'someMethod'? – michaJlS

+0

我不注入方法,我只是聲明導入,是這個問題? – ps0604

回答

2

首先爲了訪問一個類的方法,你必須有這個類的實例。在您使用依賴注入時,您需要首先將singleton類注入要使用該方法的類中。所以首先聲明類讓我們說Foo並使用Guice註解@Inject注入類MySingleton然後一旦你得到類的引用(實例)。您可以使用.

調用someMethod如果您想訪問類中的方法,例如Foo。你需要注入類MySingleton

import p1.MySingleton 

class Foo @Inject() (mySingleton: MySingleton) { 

    //This line could be any where inside the class. 
    mySingleton.someMethod 

} 

另一種使用Guice噴射的方法。

import p1.MySingleton 

class Foo() { 
    @Inject val mySingleton: MySingleton 

    //This line could be any where inside the class. 
    mySingleton.someMethod 

} 
0

這不是一個真正的斯卡拉單身人士,所以你不能訪問someMethod靜態。 @Singleton註釋告訴DI框架僅在應用程序中實例化類的一個,以便注入它的所有組件都獲得相同的實例。

如果你想使用someMethod從一個叫Foo類,你需要做這樣的事情:

class Foo @Inject() (ms: MySingleton) { 

    // call it somewhere within the clas 
    ms.someMethod() 

}