Search code examples
javaandroiddagger-2

How to inject pojo dependencies using dagger 2?


I have a simple pojo class:

public class MySimpleClass {

    private List<String> mDependency;

    public MySimpleClass (List<String> dependency) {
        mDependency = dependency;
    }
}

And I'm trying to have it created using dependency injection using dagger 2. Right now I have a simple module and component for it:

@Module
public class MySimpleClassModule {

    @Provides
    MySimpleClass provideMySimpleClass(List<String> dependency) {
        return new MySimpleClass(dependency);
    }
}

@Component(modules={MySimpleClassModule.class})
public interface MySimpleClassComponent {
}

But I'm not sure how can I inject the List<String> dependency every time I need to create a new instance of MySimpleClass. In the above scenario, it seems I would actually need to add List<String> to the constructor of MySimpleClassModule and have a new instance of that module every time I need a new instance of MySimpleClass with a new List<String>. Is that correct? It seems like a lot of overhead in this particular case.


Solution

  • If you get to define the constructor of an object it is best to use an @Inject constructor. Dagger 2 will automatically know how to instantiate the object so you won't need a @Provides annotated method in a module.

    public class MySimpleClass {
    
        private List<String> mDependency;
    
        @Inject
        public MySimpleClass (List<String> dependency) {
            mDependency = dependency;
        }
    }
    

    Dagger will assume that the parameters of the constructor are dependencies and try to resolve them from the dependency graph. Note that you can only have one @Inject annotated constructor per class! If you cannot instantiate the object yourself (e.g. Android Activities/Fragments) you need to use field injection.

    In your case it doesn't seem necessary to inject an empty list into MyClass. You can just instantiate the list in the constructor. However, when you want to inject MyClass into another object it will already be in the object graph.