user3057944 user3057944 - 4 months ago 10
Java Question

How to inject object with args in it's constructor with Dagger2


Now I modified my code like this, and it works, but I don't know is this the proper way.

the class

this is the injection

I'm learning how to use dagger2 in my project, but I don't know how to inject this dependency.
I have a test calss with a constructor where I've to pass 3 args that comes from the activity where to I want to inject my class.
Here is my test class:
Here is my module for my test class: and this is my component:

and here how I'd like to use the injection, but it isn't work:

Can I somehow inject objects like this, or how can I pass args to injected object?


If you don't have any other dependency in this class, then maybe it's not really a dependency of your activity and you could just use a new. But to answer your question, you'd want to have a subcomponent for your activity (or activities of this kind) with a module like this:

public class TestModule {
  private final String arg1;
  private final int arg2;
  private final boolean arg3;

  public TestModule(String arg1, int arg2, boolean arg3) {
    this.arg1 = arg1;
    this.arg2 = arg2;
    this.arg3 = arg3;

  @Provides DaggerTestClass provideDaggerTestClass() {
    return new DaggerTestClass(arg1, arg2, arg3);

and you'd use it like:

    .daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))

If you have other dependencies in this class though, then you'd probably want to actually use a factory (possibly generated for you using AutoFactory), then "manually inject" the created object:

private DaggerTestClass daggerTestClass; // note: no @Inject here

// …

// Inject other dependencies into the activity
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
    .daggerTestFactory().create("arg1", 2, true);