详解 Dagger2 的 @Scope 和 @Subcomponent

本文详细介绍了Dagger2中的@Scope和@Subcomponent的使用,通过实例解释了它们在Android开发中的作用。@Scope用于实现类似单例的作用域,而@Subcomponent则用于组件间的依赖关系,特别是当需要子Component从父Component继承或扩展功能时。文章还探讨了如何避免误解和常见问题,提供了实际场景的应用解析。
摘要由CSDN通过智能技术生成

个人觉得网上关于 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值