问题
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");
}
}
After experimenting with Dagger 2 for a while I have no idea how to use constructor injection – a hint would be nice, thanks.
Edit:
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?
回答1:
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();
}
An instance of Dog can then be retrived by calling [Component].dog()
.
final ActivityComponent comp = DaggerActivityComponent.builder()
.applicationComponent(app.getApplicationComponent())
.build();
final Dog d = comp.dog();
来源:https://stackoverflow.com/questions/29867637/how-to-create-an-object-using-constructor-injection