Dagger 2注入构造函数的参数

时间:2015-08-18 15:12:59

标签: android dagger-2

我在Dagger 2 website上看到了以下示例:

class Thermosiphon implements Pump {
  private final Heater heater;

  @Inject
  Thermosiphon(Heater heater) {
    this.heater = heater;
  }

  ...
}

和文档:

  

当请求新实例时,Dagger将获得所需的实例   参数值并调用此构造函数。

当我编写模块以提供Thermosiphon之类的

@Module
public class ThermosiphonModule {

    @Provides
    @Singleton
    Thermosiphon provideThermosiphon() {
        return new Thermosiphon(???);
    }

}

Thermosiphon构造函数仍然需要Heater作为参数,从而呈现整个构造函数依赖关系的自动注入。无用。

我试过

return new Thermosiphon(null); 

return new Thermosiphon(); 

(空构造函数)并希望Dagger2能够获取我希望注入缺少的Heater,但所提供的Thermosiphon的加热器始终为空;

虽然我的HeaterComponent / HeaterModule工作正常并且能够提供Heater,但我已经过验证。

我是否完全误解了Dagger的整个功能,以满足您的构造函数依赖性。或者我错过了什么?

2 个答案:

答案 0 :(得分:51)

如果您正在使用模块,那么如果您有两个提供者模块绑定到同一个组件,那么您将能够允许他们将加热器视为构造函数参数。

@Module
public class HeaterModule {
    @Provides
    @Singleton
    Heater heater() {
        return new Heater(); // if not using @Inject constructor
    }
}

@Module
public class ThermosiphonModule {
    @Provides
    @Singleton
    Thermosiphon thermosiphon(Heater heater) {
        return new Thermosiphon(heater); // if not using @Inject constructor
    }
}

@Singleton
@Component(modules={ThermosiphonModule.class, HeaterModule.class})
public interface SingletonComponent {
    Thermosiphon thermosiphon();
    Heater heater();

    void inject(Something something);
}

public class CustomApplication extends Application {
    private SingletonComponent singletonComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        this.singletonComponent = DaggerSingletonComponent.builder().build(); //.create();
    }

    public SingletonComponent getSingletonComponent() {
        return singletonComponent;
    }
}

但是使用构造函数注入,只要它们具有@Inject构造函数,您还可以提供给定范围的对象或未编组的对象。

例如,

@Singleton
@Component // no modules
public interface SingletonComponent {
    Thermosiphon thermosiphon();
    Heater heater();

    void inject(Something something);
}

@Singleton
public class Heater {
    @Inject
    public Heater() {
    }
}

@Singleton
public class Thermosiphon {
    private Heater heater;

    @Inject
    public Thermosiphon(Heater heater) {
        this.heater = heater;
    }
}

或者

@Singleton
public class Thermosiphon {
    @Inject
    Heater heater;

    @Inject
    public Thermosiphon() {
    }
}

答案 1 :(得分:28)

首先,由于您已使用Thermosiphon@Inject的构造函数进行了注释,因此您不需要@Provides方法。 Dagger使用此构造函数在需要时创建实例。只需使用Thermosiphon注释@Singleton类本身,以保留单例行为。

如果您确实想使用@Provides方法并完全回答您的问题,可以指定Heater作为方法的参数:

@Module
public class ThermosiphonModule {

    @Provides
    @Singleton
    Thermosiphon provideThermosiphon(Heater heater) {
        return new Thermosiphon(heater);
    }

}
相关问题