史上最适合新手的Dagger2教程(四)带参注入

Dagger2系列教程目录:

史上最适合新手的Dagger2教程(一)基本注入

史上最适合新手的Dagger2教程(二)对象注入

史上最适合新手的Dagger2教程(三)模型与单例

 史上最适合新手的Dagger2教程(四)带参注入

史上最适合新手的Dagger2教程(五)命名、限定与延时加载

前面我们讲解了构造方法中不带参数的各种注入方式,

这节课,我们来学习构造方法中带参数的对象如何使用Dagger2注入。

· 常规实现

我们先不使用Dagger2,以常规的方式注入一个带参构造的对象:

带参构造类:

public class SellMoe {
    private int age;

    public SellMoe(int age) {
        this.age = age;
    }

    public String sellMoe() {
        return "我特么" + age + "岁了还是可爱得要死";
    }
}

常规调用:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);
        
        SellMoe sellMoe = new SellMoe(80);
        textView.setText(sellMoe.sellMoe());
    }
}

运行结果:

接下来我们使用Dagger2来注入它。

· Dagger2注入

下面所用到的注解,在上节课有详细的说明,如果不熟练请回顾上一节。

Step1:创建带参构造模型(@Module)

对于带参构造的对象,必须使用@Module注入;并且这个模型必须有一个带参的构造方法

@Module
public class SellMoeModule {
    private int age;

    public SellMoeModule(int age) {
        this.age = age;
    }
}

Step2:创建带参提供者(@Provides)

除了提供带参的对象的提供者以外,还要有提供参数的提供者,二者缺一不可

@Module
public class SellMoeModule {
    private int age;

    public SellMoeModule(int age) {
        this.age = age;
    }

    //提供参数的提供者
    @Provides
    public int ageProvider() {
        return age;
    }

    //提供对象的提供者
    @Provides
    public SellMoe sellMoeProvider(int age) {
        return new SellMoe(age);
    }

}

传参的事情交给提供者来完成。

Step3:创建注入器(@Component)

带参的注入器必须指定使用的模型:

//指定模型
@Component(modules = SellMoeModule.class)
public interface SellMoeComponent {
    void inject(MainActivity mainActivity);
}

Step4:构建项目,生成注入器

反正养成习惯写完注入器就Build一次就对了!

Step5:注入对象

使用带参模型注入的时候,就不能直接使用create()方法了,

和需要更改OkHttp3的参数时,需要使用OkHttpClient.Builder()一个道理,

这里也要使用Builder()传入带参的Module:

public class MainActivity extends AppCompatActivity {

    @Inject
    SellMoe sellMoe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.textView);

        DaggerSellMoeComponent.builder().sellMoeModule(new SellMoeModule(80)).build().inject(this);

        textView.setText(sellMoe.sellMoe());
    }
}

以上就是带参对象的注入过程。

但是话又说回来,有时候一个对象,有带参和不带参两个构建方法,这个时候怎么办嘞?

下节课再讲!

· 家庭作业

用Dagger2注入一个带参数的杠精类,分别使用普通模式和单例模式:

public class GangJing {
    private int age;

    public GangJing(int age) {
        this.age = age;
    }

    public String gang() {
        return "我特么" + age + "岁了抬起杠来依然是个扛把子";
    }
}

猜你喜欢

转载自blog.csdn.net/u014653815/article/details/81219902