缺省情況下,Guice 每次都創(chuàng)建類的一個(gè)新的實(shí)例對(duì)象給需要該類實(shí)例的地方??梢允褂?Scopes 來(lái)修改這個(gè)缺省行為,Scope 允許在一定范圍內(nèi)重用類實(shí)例。Roboguice 中常用的有兩種:
使用 Scope 的方法為使用相應(yīng)的標(biāo)記,如:
@Singleton
public class InMemoryTransactionLog implements TransactionLog {
// everything here should be threadsafe!
}
或者在 Module 中使用 bind 語(yǔ)句:
bind(TransactionLog.class)
.to(InMemoryTransactionLog.class)
.in(Singleton.class);
如果使用 @Provides,可以有:
@Provides @Singleton
TransactionLog provideTransactionLog() {
...
}
如果某個(gè)類型使用某個(gè)你不想使用的 Scope 標(biāo)記,可以將其綁定到 Scopes.NO_SCOPE 取消這個(gè) Scope 定義。