dagger2 学习

dagger2 依赖注入框架   编译期间自动生成代码,负责依赖对象的创建  目的降低程序的耦合性

 添加依赖:(基于android studio 3.1.3版本)

  

dependencies{
    //...
compile 'com.google.dagger:dagger:2.7'
annotationProcessor 'com.google.dagger:dagger-compiler:2.7'
}

Activity 代码 片段  (dagger 结合mvp 简单的demo)


//======================================================

//BluetoothPresenter 为接口 @Inject 用来标记需要注入的依赖对象,@Module 类中会提供

//BluetoothPresenter 的实例 BluetoothPresenterImpl
@Inject  
BluetoothPresenter bluetoothPresenter;

private BluetoothActivityComponent bluetoothActivityComponent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    bluetoothActivityComponent = DaggerBluetoothActivityComponent.builder().
            bluetoothModule(new BluetoothModule(this)).build();
    bluetoothActivityComponent.inject(this);

}

//=============================================================

public interface BluetoothPresenter {
    String getString();
}


//============================================================

//Component 可以理解为将目标类实例注入到需要依赖的类中 这里是一个activity  ,

@ActivityScope
@Component(modules = BluetoothModule.class)
public interface BluetoothActivityComponent {
    void inject(BluetoothActivity bluetoothActivity);
}


@Scope
@Retention(value = RetentionPolicy.RUNTIME)
public @interface ActivityScope {

}

//=======================================================

//@Module 用来告诉Component 可以从中获取所需要依赖的实例对象

@Module
public class BluetoothModule {

    private BluetoothView bluetoothView;

    public BluetoothModule(BluetoothView bluetoothView ){
        this.bluetoothView = bluetoothView;
    }



// @Provides 标注方法是 用来生成所需要的实例对象
    @Provides
    BluetoothView provideBluetoothView(){
        return bluetoothView;
    }


    @ActivityScope
    @Provides
    BluetoothPresenter providePresenter(){
//此处提供BluetoothPresenter 的实例有需要BluetoothView的实例
//这次是通过@Module 标注类的构造方法来传入Bluetoothview 的实例即activity
        return new BluetoothPresenterImpl(this.bluetoothView);
    }

}


//=========================================================

public class BluetoothPresenterImpl implements BluetoothPresenter {

    private BluetoothView bluetoothView;

//用@Inject 标注此处,是因为BluetoothView 也需要去注入一个依赖对象
    @Inject
    public BluetoothPresenterImpl(BluetoothView bluetoothView) {
        this.bluetoothView = bluetoothView;
    }


    @Override
    public String getString() {
        return "txt";
    }
}
先总结到这,后续在补充 2018-6-28



你可能感兴趣的:(dagger2 学习)