How to create an object using constructor injection?

爱⌒轻易说出口 提交于 2019-12-03 11:53:18

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!