Dagger 2 - Lack of Constructor Injection example

2019-05-26 17:25发布

I spend several hours for searching but I still don't find any clearly example about Constructor Injection with Dagger 2.

Assume I have below declaration, how can I create an instance of class B somewhere using Dagger 2 injection?

@Module
public class ClassA {
    @Provides public ClassA provideA(){
        return new ClassA();
    }
}
public class ClassB{
    private ClassA a;
    @Inject public ClassB(ClassA a){
        this.a = a;
    }
}

1条回答
淡お忘
2楼-- · 2019-05-26 17:53

If you have

@Module
public class ModuleA {
    /*unscoped*/ @Provides public ClassA provideA(){
        return new ClassA();
    }
}

/*unscoped*/
public class ClassB{
    private ClassA a;

    @Inject public ClassB(ClassA a){
        this.a = a;
    }
}

Then you'll need

/*unscoped*/
@Component(modules={ModuleA.class})
public interface MyComponent {
    ClassA classA();
    ClassB classB();
}

And then you can either access like so

MyComponent component = DaggerMyComponent.create();
ClassB classB = component.classB();

Or

/*unscoped*/
@Component(modules={ModuleA.class})
public interface MyComponent {
    ClassA classA();
    ClassB classB();

    void inject(MyClass myClass);
}

And

public class MyClass {
    @Inject
    ClassB classB;

    public void init() {
        MyComponent component = getComponent();
        component.inject(this);
    }
}
查看更多
登录 后发表回答