缺省情况下,Guice每次都创建类的一个新的实例对象给需要该类实例的地方。可以使用Scopes来修改这个缺省行为,Scope允许在一定范围内重用类实例。Roboguice中常用的有两种:
使用Scope 的方法为使用相应的标记,如:
- @Singleton
- public class InMemoryTransactionLog implements TransactionLog {
- // everything here should be threadsafe!
- }
或者在Module中使用bind 语句:
- bind(TransactionLog.class)
- .to(InMemoryTransactionLog.class)
- .in(Singleton.class);
如果使用@Provides,可以有:
- @Provides @Singleton
- TransactionLog provideTransactionLog() {
- ...
- }
如果某个类型使用某个你不想使用的Scope标记,可以将其绑定到Scopes.NO_SCOPE取消这个Scope定义。