废话少说,下边开始先交代原始代码场景逻辑
顺便贴一下,@Singleton注解如下
@Scope @Documented @Retention(RUNTIME) public @interface Singleton {}其所依赖的module如下
@Module public class DemoModule { private DemoActivity mActivity; @Inject public DemoModule(DemoActivity activity){ mActivity = activity; } @ActivityScope @Provides DemoActivity provideDemoActivity() { return mActivity; } }DemoActivity如下
public class DemoActivity { private DemoComponent mComponent; //代码省略 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupComponent(); } private void setupComponent() { //DaggerDemoComponent是dagger自动生成的类 下边分析的入口就是它 mComponent=DaggerDemoComponent.builder().demoModule(new DemoModule(this)).build(); mComponent.inject(this); } //代码省略 }接下来看看DoubleCheck#provider里发生了什么
public static <T> Provider<T> provider(Provider<T> delegate) { checkNotNull(delegate); if (delegate instanceof DoubleCheck) { //如果delegate是DoubleCheck类型就直接返回 //第一次不是DoubleCheck类型(是Factory<T>,最终继承自Provider<T>) //所以会在第一次build时新建一个DoubleCheck<T>实例,而之后会直接返回该实例 return delegate; } return new DoubleCheck<T>(delegate); } 也就是说此时provideDemoActivityProvider是DoubleCheck<DemoActivity>类型的对象那么DoubleCheck.provider的参数貌似在有@Scope注解时没有起作用,其实这是故意避免的,因为通过其提供的get方法得到的是DemoModule#provideDemoActivity(),也就不能保证单例性,看一下其源码:
public final class DemoModule_ProvideDemoActivityFactory implements Factory<DemoActivity>{ private final DemoModule module; public DemoModule_ProvideDemoActivityFactory(DemoModule module) { assert module != null; this.module = module; } @Override public DemoActivity get() { return Preconditions.checkNotNull( //当没有@Scope注解时提供依赖的方法会走这 module.provideDemoActivity(), "Cannot return null from a non-@Nullable @Provides method"); } public static Factory<DemoActivity> create(DemoModule module) { return new DemoModule_ProvideDemoActivityFactory(module); } }到这就很清楚了,之所以@Scope类型注解能让其保持单例,是因为DoubleCheck#get方法实现了单例:
@Override public T get() { Object result = instance; if (result == UNINITIALIZED) { synchronized (this) { result = instance; if (result == UNINITIALIZED) { // instance = result = provider.get(); provider = null; } } } return (T) result; }可能有不准确的地方,欢迎指正