How do I 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;
}
}
I’m trying to create it using Dagger 2 using dependency injection (inject). Now I have a simple module and component:
@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 to inject List<String>
every time I need to create a new instance of MySimpleClass
depend. In the above scenario, it seems like I actually need to add a List<String> constructor to MySimpleClassModule
every time I need a new instance of MySimpleClass
, with a new List
<String>
Is that right? In this particular case, the overhead seems significant.
Solution
No, it’s not.
I’m assuming you’re getting a Dagger compilation error, because it’s unclear from the question whether you already have a module that provides this list of strings.
To solve this problem, you can simply:
@Module
public class MySimpleClassModule {
@Provides
List<String> provideListDependency() {
return Arrays.asList("One", "Two");
}
@Provides
MySimpleClass provideMySimpleClass(List<String> dependency) {
return new MySimpleClass(dependency);
}
}
If you think that providing this list should be part of another module, you can move it. The main thing is that Dagger was able to find a way to get this dependency during compilation.
If you don’t want to create this array in over, you can mark the method as @Singlethon
so that the dagger caches it.