Dagger2

参考
Android_Dagger2篇——从小白最易上手的角度 + 最新dagger.android
都是套路——Dagger2没有想象的那么难

一、无module方式,无参构造

(最简单,但是不常用)

1. 在需要实例化的类中,构造无参构造方法,注解@Inject

必须是无参构造方法

@Inject
public Student() {
}

2. 构造Component接口,有inject方法

@Component
public interface DaggerComponent {
    void inject(MainActivity activity);    //要注入的类
}

3. Make Project (Ctrl+F9)

4. 在需要注入的类中调用

@Inject
Student mStudent;
DaggerStudentComponent.create().inject(this);   //该方法执行成功即可以调用对象

二、有module方式

1. 在需要实例化的类中,构造方法注解@Inject

可以带有参数

@Inject
public Student(String name, int age) {
    this.name = name;
    this.age = age;
}

2. 构造Module类

  • 注解@Module
  • 构造一个返回类型为需要注入对象的方法,注解@Provides
@Module
public class StudentModule {
    @Provides
    Student provideStudent() {
        return new Student("张三", 18);
    }
}

3. 构造Component接口,有inject方法

@Component(modules = StudentModule.class)   //与上面唯一的区别在此
public interface StudentComponent {
    void inject(MainActivity activity);
}

4. 在需要注入的类中调用

使用builder方式而不是create注入

@Inject
Student mStudent;
DaggerStudentComponent.builder().studentModule(new StudentModule()).build().inject(this);

注意

  1. @Inject只能注解一个构造方法
  2. @Module级别高于@Inject
  3. @Component可以标注接口,也可以标注抽象类
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值