Android RoboGuice 使用指南(11): Scopes
2012-05-04 06:50
423 查看
缺省情况下,Guice每次都创建类的一个新的实例对象给需要该类实例的地方。可以使用Scopes来修改这个缺省行为,Scope允许在一定范围内重用类实例。Roboguice中常用的有两种:
@Singleton 整个Application生命周期中使用同一实例对象
@ContextScoped 同一个Context(如Activity)中共享某一实例对象。
使用Scope 的方法为使用相应的标记,如:
或者在Module中使用bind 语句:
如果使用@Provides,可以有:
如果某个类型使用某个你不想使用的Scope标记,可以将其绑定到Scopes.NO_SCOPE取消这个Scope定义。
@Singleton 整个Application生命周期中使用同一实例对象
@ContextScoped 同一个Context(如Activity)中共享某一实例对象。
使用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定义。
相关文章推荐
- Android RoboGuice 使用指南(18):Inject Resources
- Android RoboGuice 使用指南
- Android RoboGuice 使用指南(19):发送接收Events
- Android RoboGuice 使用指南2
- Android RoboGuice 使用指南(1):概述
- Android RoboGuice 使用指南(2):第一个例子Hello World
- Android RoboGuice 使用指南(6):Instance Bindings
- Android RoboGuice 使用指南(3):Bindings 概述
- Android RoboGuice 使用指南(7):@Provides Methods
- Android RoboGuice 使用指南(8):Provider Bindings
- Android RoboGuice 使用指南(4):Linked Bindings
- Android RoboGuice 使用指南(9):Untargetted Bindings
- Android RoboGuice 使用指南
- Android RoboGuice 使用指南(10): Just-in-time Bindings
- Android RoboGuice 使用指南(5):Binding Annotations
- Android RoboGuice 使用指南(12):如何绑定generic类型
- Android RoboGuice 使用指南(13):RoboGuice 功能描述
- Android RoboGuice 使用指南(14):Inject View
- Android RoboGuice 使用指南(15):Inject Context
- Android RoboGuice 使用指南(16):Standard Injection