如何使用 Dagger2 在其构造函数中注入带参数的对象
How to inject object with args in it's constructor with Dagger2
更新
现在我像这样修改了我的代码,它可以工作,但我不知道这是不是正确的方法。
classhttp://pastebin.com/srhu4eB7
这是注入http://pastebin.com/wLbxBQqb
我正在学习如何在我的项目中使用 dagger2,但我不知道如何注入此依赖项。
我有一个带有构造函数的测试 calss,我必须传递来自 activity 的 3 个参数,我想在其中注入我的 class。
这是我的测试class:http://pastebin.com/XqRNFbvj
这是我的模块,用于我的测试class:http://pastebin.com/r4wmqfLB and this is my component: http://pastebin.com/r1QYdNJx
这里我想如何使用注入,但它不起作用:http://pastebin.com/cs0V5wfq
我能否以某种方式注入这样的对象,或者我如何将 args 传递给注入的对象?
如果您在此 class 中没有任何其他依赖项,那么它可能并不是您的 activity 的真正 依赖项,您可以使用 new
。但是要回答您的问题,您需要为您的 activity(或此类活动)创建一个子组件,并使用如下模块:
@Module
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);
}
}
你会像这样使用它:
IndexApplication.getApplication().getAppComponent()
.daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))
.inject(this);
如果您在此 class 中有其他依赖项,那么您可能想要实际使用工厂(可能使用 AutoFactory 为您生成),然后 "manually inject"创建对象:
private DaggerTestClass daggerTestClass; // note: no @Inject here
// …
// Inject other dependencies into the activity
IndexApplication.getApplication().getAppComponent().inject(this);
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
.daggerTestFactory().create("arg1", 2, true);
更新
现在我像这样修改了我的代码,它可以工作,但我不知道这是不是正确的方法。
classhttp://pastebin.com/srhu4eB7
这是注入http://pastebin.com/wLbxBQqb
我正在学习如何在我的项目中使用 dagger2,但我不知道如何注入此依赖项。
我有一个带有构造函数的测试 calss,我必须传递来自 activity 的 3 个参数,我想在其中注入我的 class。
这是我的测试class:http://pastebin.com/XqRNFbvj
这是我的模块,用于我的测试class:http://pastebin.com/r4wmqfLB and this is my component: http://pastebin.com/r1QYdNJx
这里我想如何使用注入,但它不起作用:http://pastebin.com/cs0V5wfq
我能否以某种方式注入这样的对象,或者我如何将 args 传递给注入的对象?
如果您在此 class 中没有任何其他依赖项,那么它可能并不是您的 activity 的真正 依赖项,您可以使用 new
。但是要回答您的问题,您需要为您的 activity(或此类活动)创建一个子组件,并使用如下模块:
@Module
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);
}
}
你会像这样使用它:
IndexApplication.getApplication().getAppComponent()
.daggerTestSubcomponent(new DaggerTestModule("arg1", 2, true))
.inject(this);
如果您在此 class 中有其他依赖项,那么您可能想要实际使用工厂(可能使用 AutoFactory 为您生成),然后 "manually inject"创建对象:
private DaggerTestClass daggerTestClass; // note: no @Inject here
// …
// Inject other dependencies into the activity
IndexApplication.getApplication().getAppComponent().inject(this);
// "manually inject" the DaggerTestClass
this.daggerTestClass = IndexApplication.getApplication().getAppComponent()
.daggerTestFactory().create("arg1", 2, true);