How to introduce 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 create it using dependency injection using dagger 2. 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 I can inject a dependency List<String>every time I need to create a new instance MySimpleClass. In the above scenario, it seems that I really need to add List<String>to the constructor MySimpleClassModuleand have a new instance of this module every time I need a new instance MySimpleClasswith a new one List<String>. It's right? In this particular case, this seems like a lot of overhead.

+4
source share
2

, @Inject. Dagger 2 , , @Provides .

public class MySimpleClass {

    private List<String> mDependency;

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

, . , @Inject ! (, Android Activities/Fragments), .

MyClass. . , MyClass , .

+1

, .

, Dagger, , , .

, :

@Module
public class MySimpleClassModule {

    @Provides
    List<String> provideListDependency() {
        return Arrays.asList("One", "Two");
    }

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

, , . , Dagger , .

, @Singlethon, .

+3

Source: https://habr.com/ru/post/1629054/


All Articles