search

Home  >  Q&A  >  body text

android - 关于dagger2的几个问题

Scope:@PerActivity 这个注解是怎么起作用的呢?

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

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
    void inject(MainActivity mainActivity);
}
 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);

    mTvUserInfo = (TextView) findViewById(R.id.tv_user_info);
    mTvAccessToken = (TextView) findViewById(R.id.tv_access_token);
}

ringa_leeringa_lee2771 days ago352

reply all(2)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 09:20:13

    Hello @PerActivitydagger2 的自定义 Scope ,可以注解在 Component接口、Moduleprovide方法、构造器注解 @Inject的类 上面,用于实现 此 Scope Local singleton in scope.
    Please refer to https://blog.piasy.com//2016/...

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:20:13

    It has nothing to do with the name of the annotation, whether it is called PerActivity or ActivityScope. Its scope is determined by who initializes your Component itself. For example, in your example, the Component is built by Activity, and its scope naturally follows that activity

    reply
    0
  • Cancelreply