依赖注入框架dagger2的@Scope注解初探(根据生成的源码进行分析)
- 为了使讨论的问题更加清晰,我将尽可能减少无关代码,但是本文贴出的代码够初步探究@Scope作用域控制原理了
- 分析结论在文章最后
废话少说,下边开始先交代原始代码场景逻辑
首先自定义一个@Scpoe注解,用来注解之后提供的依赖
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {}
顺便贴一下,@Singleton注解如下
@Documented
@Retention(RUNTIME)
Singleton {}
然后定义Component
@ActivityScope
@Component(modules = DemoModule.class)
public DemoComponent {
DemoActivity inject(DemoActivity activity);
}
其所依赖的module如下
@Module
class DemoModule {
private DemoActivity mActivity;
@Inject
public DemoModule(DemoActivity activity){
mActivity = activity;
}
@ActivityScope
@Provides
DemoActivity provideDemoActivity() {
return mActivity;
}
}
DemoActivity如下
DemoActivity {
private DemoComponent mComponent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupComponent();
}
private void setupComponent() {
mComponent=DaggerDemoComponent.builder().demoModule(new DemoModule(this)).build();
mComponent.inject(this);
}
}
/*在DaggerDemoComponent.builder().demoModule(new DemoModule(this)).build()时会调用initialize初始化*/
void initialize(final Builder builder) {
private Provider<DemoActivity> provideDemoActivityProvider;
this.provideDemoActivityProvider = DoubleCheck.provider(DemoModule_ProvideDemoActivityFactory.create(builder.demoModule));
}
接下来看看DoubleCheck#provider里发生了什么
static <T> Provider<T> provider(Provider<T> delegate) {
checkNotNull(delegate);
if (delegate instanceof DoubleCheck) {
return delegate;
}
new DoubleCheck<T>(delegate);
}
也就是说此时provideDemoActivityProvider是DoubleCheck<DemoActivity>类型的对象
那么DoubleCheck.provider的参数貌似在有@Scope注解时没有起作用,其实这是故意避免的,因为通过其提供的get方法得到的是DemoModule#provideDemoActivity(),也就不能保证单例性,看一下其源码:
final DemoModule_ProvideDemoActivityFactory implements Factory<DemoActivity>{
final DemoModule module;
public DemoModule_ProvideDemoActivityFactory(DemoModule module) {
assert module != null;
this.module = module;
}
@Override
public DemoActivity get() {
return Preconditions.checkNotNull(
module.provideDemoActivity(),"Cannot return null from a non-@Nullable @Provides method");
}
static Factory<DemoActivity> create(DemoModule module) {
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;
}
梳理一下
- Component注入依赖时会在build方法中执行initialize
- 而在initialize中dagger会根据是否有对应的@Scope注解生成不同的代码
- 若有@Scope注解,Provider是DoubleCheck类型,否之是对应的工厂类
- DoubleCheck构造次数(即Component#build次数)决定了@Scope所注解的只是”假单例”,当然,若Provider所提供的本身就是单例那么不受影响,其仍然是单例的
- 由此推断,@Scope只能在Component所注入的作用域内保持“单例”
- 在Application中注入的是全局单例
可能有不准确的地方,欢迎指正
原文链接:https://www.f2er.com/javaschema/283261.html