如何使用构造函数注入创建对象? [英] How to create an object using constructor injection?
问题描述
我将如何使用提供Cat的组件创建Dog实例。
How would I create an instance of Dog with a component which provides Cat.
public final class Dog {
private final Cat mCat;
public final static String TAG = "Dog";
@Inject public Dog(Cat cat) {
mCat = cat;
Log.e(TAG, "Dog class created");
}
}
尝试使用Dagger 2一段时间后,我没有
After experimenting with Dagger 2 for a while I have no idea how to use constructor injection – a hint would be nice, thanks.
编辑:
,请问如何使用构造函数注入的想法。题?使用Dagger 2之后,按照一些教程并阅读了官方文档后,我不知道如何使用构造函数注入功能,这就是为什么我在这里问。不用使用@Inject将Cat依赖项注入Dog,我可以编写一个提供Dog对象的DogModule,但是Dog只是一个普通的Java类。字段注入效果很好(有很多示例说明了如何使用它),但是使用构造函数注入需要做什么?
Whats wrong with the question? After using Dagger 2, following several tutorials and reading the official documentation I have no clue how to use the constructor injection feature, that's why I ask here. Instead of injecting the Cat dependency into Dog with @Inject I could write a DogModule providing a Dog object, but then Dog would be just a regular Java class. Field injection works great (there are a lot of examples showing how to use it) but what do I need to do to use constructor injection?
推荐答案
要使用Dagger 2构造函数注入功能创建对象,您需要向提供Cat类的组件添加方法。
To create an object using the Dagger 2 constructor injection feature you need to add a method to a component which provides a Cat class.
@Component(
dependencies = ApplicationComponent.class,
modules = CatModule.class)
public interface ActivityComponent {
void inject(final CatActivity a);
// objects exposed to sub-components
Cat cat();
Dog dog();
}
然后可以通过调用来检索Dog的实例[Component] .dog()
。
final ActivityComponent comp = DaggerActivityComponent.builder()
.applicationComponent(app.getApplicationComponent())
.build();
final Dog d = comp.dog();
这篇关于如何使用构造函数注入创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!