@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);
}
大家讲道理2017-04-18 09:20:13
Hello @PerActivity
是 dagger2
的自定义 Scope
,可以注解在 Component
接口、Module
的provide
方法、构造器注解 @Inject
的类 上面,用于实现 此 Scope
Local singleton in scope.
Please refer to https://blog.piasy.com//2016/...
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