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