美文网首页
Dagger2 Singleton 注解

Dagger2 Singleton 注解

作者: lyzaijs | 来源:发表于2016-03-08 23:00 被阅读1967次

Dagger2学习过程中一直以为被 @single注解会有类似static效果(效果相同只是实现方式并不是static,下面会提到双重检查锁)。无意找到如下说明

@Singleton
means there will be one instance of the object for the lifetime of the component, not for the lifetime of the JVM.
and
Adding a scope annotation to a @Provides
method means that the method will be called at most once within one instance of the component it's installed into. Without that, the @Provides
method would be called again every time a Provider
's get()
method is called, even within one component instance. Every class that @Injects
a RestRepository
would get a new instance

@single dagger2会在生成的DaggerxxComponent文件的初始化方法中以 ScopedProvider 包裹提供依赖:

DaggerxxComponent.java

private void initialize(final Builder builder) { 

 this.providesAnimProvider = ScopedProvider.create(AnimModule_ProvidesAnimFactory.create(builder.animModule));

 }

ScopeProvider.java 单例模式 - 双重检查锁模式

 public T get() {
 // double-check idiom from EJ2: Item 71
 Object result = instance;
 if (result == UNINITIALIZED) {
 synchronized (this) {
 result = instance;
 if (result == UNINITIALIZED) {
 instance = result = factory.get();
 }
 }
 }
 return (T) result;
 }

Adding a scope annotation to a @Providesmethod means that the method will be called at most once within one instance of the component it's installed into.
达到以上效果是通过ScopeProvider的get方法控制的。

相关文章

网友评论

      本文标题:Dagger2 Singleton 注解

      本文链接:https://www.haomeiwen.com/subject/pyvzkttx.html