从 Dagger2 源码角度理解 Scope 注解

本文主要从Dagger2生成的源码角度讲解Scope注解的作用

代码已上传至GitHub,戳github.com/tb-yangshu/…,欢迎star或者fork

Scope

Identifies scope annotations. A scope annotation applies to a class containing an injectable constructor and governs how the injector reuses instances of the type. By default, if no scope annotation is present, the injector creates an instance (by injecting the type’s constructor), uses the instance for one injection, and then forgets it. If a scope annotation is present, the injector may retain the instance for possible reuse in a later injection. If multiple threads can access a scoped instance, its implementation should be thread safe. The implementation of the scope itself is left up to the injector.

以上解释来源于docs.oracle.com/javaee/7/ap…

意思是,Scope注解被标注在可被注入类的构造器上,注入器根据Scope类型来决定如何对实例进行复用。默认情况下,被注入类上没有Scope注解,此时注入器每次注入都会生成新的实例并注入。如果标注了Scope注解,注入器创建成功实例后会将其缓存,在下次注入时直接返回缓存结果。多线程模式下可以访问同一个被Scope标注的实例,因为该实例是线程安全的。注入器将会生成Scope的具体实现类。

Singleton

Singleton是由javax.inject包提供的,用来控制被注入实例被创建后进行缓存复用。

@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {}

Custom Scope

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface PerActivity {
}

PerActivity用来标注被注入类和与之对应的Component,来控制被注入实例在Activity生命周期中可以被复用。

源码分析

接下来,从Dagger2生成的代码来分析Scope注解的作用。源码地址

以下是使用Dagger2为MainActivity注入ActivityDataActivityDataWithScope实例的代码。

ActivityComponent.java

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}

ActivityData.java

public class ActivityData {
    @Inject
    public ActivityData() {
    }
}

ActivityDataWithScope.java

@PerActivity
public class ActivityDataWithScope {

    @Inject
    public ActivityDataWithScope() {
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ...

    @Inject
    ActivityData mActivityData;

    @Inject
    ActivityDataWithScope mActivityDataWithScope;

    private ActivityComponent activityComponent;

    ...

    public ActivityComponent getActivityComponent() {
        if (activityComponent == null) {
            activityComponent = DaggerActivityComponent.builder()
                    .activityModule(new ActivityModule(this))
                    .applicationComponent(DemoApplication.get(this).getComponent())
                    .build();
        }
        return activityComponent;
    }

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          // 注入实例
        getActivityComponent().inject(this);

         ...
    }
    ...
}

从上面的代码可以看出,使用Dagger2寥寥数行代码就实现了实例的注入,极大的节省了开发时间,省去了手动new的操作,代码也看起来更加优雅,美观。

下面从Dagger2生成的ActivityComponent实现类DaggerActivityComponent来分析依赖注入的实现流程。

DaggerActivityComponent.java

@Generated(
  value = "dagger.internal.codegen.ComponentProcessor",
  comments = "https://google.github.io/dagger"
)
public final class DaggerActivityComponent implements ActivityComponent {
  ...
  private Provider<ActivityData> activityDataProvider;

  private MembersInjector<MainActivity> mainActivityMembersInjector;

  private DaggerActivityComponent(Builder builder) {
    assert builder != null;
    initialize(builder);
  }

  public static Builder builder() {
    return new Builder();
  }

  @SuppressWarnings("unchecked")
  private void initialize(final Builder builder) {
       ...
    this.activityDataWithScopeProvider =
        DoubleCheck.provider(ActivityDataWithScope_Factory.create());

    this.mainActivityMembersInjector =
        MainActivity_MembersInjector.create(
            getDataManagerProvider, ActivityData_Factory.create(), activityDataWithScopeProvider);
  }

  @Override
  public void inject(MainActivity mainActivity) {
    mainActivityMembersInjector.injectMembers(mainActivity);
  }

  public static final class Builder {
    private ApplicationComponent applicationComponent;

    private Builder() {}

    public ActivityComponent build() {
      if (applicationComponent == null) {
        throw new IllegalStateException(
            ApplicationComponent.class.getCanonicalName() + " must be set");
      }
      return new DaggerActivityComponent(this);
    }
       ...
  }
}

该类使用了Builder模式来创建ActivityComponent实例。这里需要留意下initialize方法,该方法创建了生产被注入实例的Provider和注入器MembersInjector的实例。

不难发现activityDataWithScopeProvider的创建过程与ActivityDataProvider稍有不同。这是由于ActvityDataWithScope被标注了PerActivity注解。

接下来比较下Dagger2生成ActivityData实例与ActivityDataWithScope实例的不同之处,这也是Scope注解的作用。

先来看一下ActivityData实例的创建方式,以下是ActivityData_Factory的代码

@Generated(
  value = "dagger.internal.codegen.ComponentProcessor",
  comments = "https://google.github.io/dagger"
)
public final class ActivityData_Factory implements Factory<ActivityData> {
  private static final ActivityData_Factory INSTANCE = new ActivityData_Factory();

  @Override
  public ActivityData get() {
    return new ActivityData();
  }

  public static Factory<ActivityData> create() {
    return INSTANCE;
  }
}

可以看出每次调用get方法都会重新返回一个新的ActivityData实例。

接下来分析ActivityDataWithScope实例的创建方式。

DoubleCheck.provider(ActivityDataWithScope_Factory.create())显然对Provider进行了再次封装。下面是DoubleCheck的代码。

public final class DoubleCheck<T> implements Provider<T>, Lazy<T> {
    private static final Object UNINITIALIZED = new Object();
    private volatile Provider<T> provider;
    private volatile Object instance;

    private DoubleCheck(Provider<T> provider) {
        this.instance = UNINITIALIZED;

        assert provider != null;

        this.provider = provider;
    }

    public T get() {
        Object result = this.instance;
        if(result == UNINITIALIZED) {
            synchronized(this) {
                result = this.instance;
                if(result == UNINITIALIZED) {
                    result = this.provider.get();
                    Object currentInstance = this.instance;
                    if(currentInstance != UNINITIALIZED && currentInstance != result) {
                        throw new IllegalStateException("Scoped provider was invoked recursively returning different results: " + currentInstance + " & " + result);
                    }

                    this.instance = result;
                    this.provider = null;
                }
            }
        }

        return result;
    }

    public static <T> Provider<T> provider(Provider<T> delegate) {
        Preconditions.checkNotNull(delegate);
        return (Provider)(delegate instanceof DoubleCheck?delegate:new DoubleCheck(delegate));
    }

    public static <T> Lazy<T> lazy(Provider<T> provider) {
        if(provider instanceof Lazy) {
            Lazy lazy = (Lazy)provider;
            return lazy;
        } else {
            return new DoubleCheck((Provider)Preconditions.checkNotNull(provider));
        }
    }
}

分析上面的get方法,不难看出是对Provider.get()返回的实例进行了缓存来实现单例。

总结

从上面的分析可以看出,Scope注解的作用就是在特定作用域内控制被注入实例的复用。

比如,从登录到退出,用户基本信息(如uid)是不会发生变化的,用来存储用户数据的实例就可以通过Scope标识来复用。

参考资料

Dagger 2 Basics

Android Dagger 2 scopes demystified

docs.oracle.com/javaee/7/ap…

    原文作者:Android源码分析
    原文地址: https://juejin.im/entry/58fff41f0ce46300614569b5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞