Dagger2学习记录

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:23   1923   0

记录一下最近学习Dagger2的认知,如有错误望指正

引入

implementation 'com.google.dagger:dagger:2.4'
annotationProcessor 'com.google.dagger:dagger-compiler:2.4'

一、 module的使用

1 class A

public class A {
    private Context context;
    private String msg;

    public A(Context context){
        this.context=context;
    }

    public String getMsg(){
       return msg;
    }

    public String setMsg(String msg){
        this.msg=msg;
        return this.msg;
    }
}

2 @Module

@Module
public class AModule {
    private Context context;
    private String msg;
    public AModule(Context context,String msg){
        this.context=context;
        this.msg=msg;
    }
    
    @Provides
    public Context provideContext(){
        return context;
    }
    @Provides
    public A provideA(){
        A a=new A(context);
        a.setMsg(msg);
        return a;
    }

3 @Component

@Component(modules =AModule.class)
public interface MainActivityComponent {
    void inject(MainActivity activity);
}

4 使用

public class MainActivity extends AppCompatActivity {

    @Inject
    A a;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DaggerMainActivityComponent.builder().aModule(new AModule(this,"this is a test")).build()
                .inject(this);
        a.getMsg();


    }
}

二、@Singleton的使用(单例模式)

如果A想作为单利模式出现,则上面代码做两处改动

1 在@Component上面添加@Singleton,在provideA()方法的@Provides的上面添加@Singleton

三、@Inject的使用

关于Inject,我这边只能实现无参数构造,不知道为什么

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP