How to create an object using constructor injection?

后端 未结 1 1311
臣服心动
臣服心动 2021-02-05 05:41

How would I create an instance of Dog with a component which provides Cat.

public final class Dog {
    private final Ca         


        
相关标签:
1条回答
  • 2021-02-05 06:21

    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();
    
    0 讨论(0)
提交回复
热议问题