Dagger2 同时引用多个 Module 的三种写法

在一个界面中,我们很多时候会同时用到两个或者以上的 Module ,这里整理一下 Dagger2 添加多Module 的用法,这里先贴一些示例需要的代码,至于基础使用方式,这里就不多说明了:

ApiService

public class ApiService {
    OkHttpClient okHttpClient;

//    @Inject
    public ApiService(OkHttpClient okHttpClient) {
        LvLog.i("ApiService: ");
        this.okHttpClient = okHttpClient;
    }
}

UserModule

@Module
public class UserModule {
    @Provides
    public ApiService provideApiService(OkHttpClient client) {
        return new ApiService(client);
    }
}

HttpModule

@Module
public class HttpModule {

    @Provides
    public OkHttpClient provideOkHttp() {
        LvLog.i("provideOkHttp: ");
        return new OkHttpClient.Builder().build();
    }
}

Component

@dagger.Component(modules = UserModule.class)
public interface Component {
    // 这里对 Module 和 Activity 进行关联
    void init(Dagger2Activity activity);
}

现在因为我们 UserModule 中 初始化 ApiService 会需要用到 OkHttpClient 实例,但是,这个实例是在 HttpModule 中实现的。那么,我们该如何去添加呢,来看一下下面的 种方式。

方式一

在 Module 注解中使用 <include> 标签

@Module(includes = {HttpModule.class})
public class UserModule {
    ...
}

方式二

在 Component 注解后添加多个 Module.

@dagger.Component(modules = {UserModule.class,HttpModule.class})
public interface Component {
    // 这里对 Module 和 Activity 进行关联
    void init(Dagger2Activity activity);
}

方式三

在 Component 中添加 dependencies 属性。

新建一个 HttpComponent,配置 HttpModule

@dagger.Component(modules = HttpModule.class)
public interface HttpComponent {
// 这里需要对外暴露出获取 OkHttpClient 的方法,方法名不需要和 HttpModule 中保持一致。
    OkHttpClient provideOkHttp();
}

ps 如果 HttpComponent 中没有提供对方暴露的方法,则会提示 cannot be provided without an @Inject constructor or from an @Provides-annotated method.

然后在 Component 引用:

@dagger.Component(modules = {UserModule.class}, dependencies = HttpComponent.class)
public interface Component {
    // 这里对 Module 和 Activity 进行关联
    void init(Dagger2Activity activity);
}

注入方式

正常情况下,一个或者多个 Module 注入方式如下:

  • 注入方式一
DaggerComponent.create().init(this);
  • 注入方式二
/// 如果 module 中需要传入参数,则可通过此种方式。
DaggerComponent.builder()
                .userModule(new UserModule())
                .httpModule(new HttpModule())  
                .build().init(this)

当然,如果 Module 中需要传入参数的时候,就只能需要使用第二种方式了,

  • 注入方式三

此外,就像我以上整理的 方式三 添加多个 Module ,这里就不能使用上面两种方式了,

这个时候就需要使用以下注入方式了:

DaggerComponent.builder()
                .userModule(new UserModule())
//                .httpComponent(DaggerHttpComponent.create())  // 调用方式一
                .httpComponent(DaggerHttpComponent.builder().httpModule(new HttpModule()).build())  // 调用方式二
                .build().init(this);

这里就整理出这些基础操作,至于需要添加其他注解,此处就不多做说明了。

示例代码

猜你喜欢

转载自blog.csdn.net/lv_fq/article/details/78777731