个人觉得网上关于 dagger2 文章中关于 @Scope
和 @Subcomponent
解释的并不是很详细,也可能是我个人能力有限不能够理解,所以写下这篇文章,希望能够帮助后人更方便的入门。
@Scope
是什么@Scpoe
的使用@Subcomponent
是什么@Subcomponent
的使用@Subcomponent
和@Component
的实际使用场景定义
@Scope
是什么
scope 翻译过来就是辖域,再结合到计算机上,其实就是作用域的意思,学过高级语言的应该都知道设计模式中一个模式叫做单例模式,单例即为全局中该对象的实例只存在一个,而在 dagger2 中,@scope
的一个默认实现就是 @Singleton
,乍一看,很神奇啊,仅仅使用一个注解就可以实现单例!
@Scpoe
怎么用
那么接下来我们就看一下它的使用。代码如下:
public class User {}
@Module
public class UserModule {
@Provides
@Singleton
User provideUser() {
return new User();
}
}
@Singleton
@Component(modules = UserModule.class)
public interface UserComponent {
void inject(MainActivity activity);
void inject(SecondActivity activity);
}
我们创建一个普通的 User
类,然后创建它的 Module,并且用 @Singleton
标记该 User 返回对象,最后我们再创建它的 Component,然后用 @Singleton
标记这个 Component。这是一个标准的套路流程。接下来我们创建一个 MainActivity
和一个 SecondActivity
,代码如下:
public class MainActivity extends AppCompatActivity {
@Inject
User mUser1;
@Inject
User mUser2;
private TextView mContentTextView;
private Button mContentButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContentTextView = (TextView) findViewById(R.id.tv_content);
mContentButton = (Button) findViewById(R.id.btn_content);
// [1]
UserComponent component = DaggerUserComponent.create();
component.inject(this);
// 第一行为 mUser1 的信息,第二行为 mUser2 的信息,第三行为该类中 UserComponent 的信息
mContentTextView.setText(mUser1.toString() + "\n" + mUser2.toString()+"\n"+ component.toString());
mContentButton.setOnClickListener(new View.OnClickListener() {
@Override