我已经用两个组件设置了 Dagger 。一个组件是另一个组件的子组件,这很重要。一切正常。但后来我随机想尝试构造函数注入(inject),所以我创建了一个随机类,并用 Inject 注释标记了它的构造函数,令我惊讶的是,当我想要注入(inject)这个类时,它可以工作吗?我的组件对此一无所知。我的组件接口(interface)中没有写关于这个类的内容。它只是一个随机类,有一个用 @Inject 注释的构造函数。这是如何运作的?这是随机类别:
public class Knife {
@Inject
public Knife(){
System.out.println("a spreading knife has been created");
};
}
如果重要的话,这里是如何调用注入(inject)我的类:
public class MainActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
//@Inject
//AlmondButter someAlmondButter;
@Inject
CashewSandwich sandwich;
@Inject
CashewSandwich sandwich2;
/*some how this is getting injected but its not in any component, how ?No ones
providing it in a module either*/
@Inject
Knife mKnife;
SandwichComponent sandwichComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*create the dependent butter for the sandwich here*/
ButterComponent butterComponent=DaggerButterComponent.builder().
butterModule(new ButterModule()).build();
/*create a scope sandwichcomponent here */
sandwichComponent=DaggerSandwichComponent.builder().sandwichModule(new SandwichModule()).
butterComponent(butterComponent)
.build();
//finally we have a sandwichComponent, lets inject our dependencies
sandwichComponent.inject(this);
Log.v(TAG," first:"+sandwich.toString());
Log.v(TAG,"second:"+sandwich2.toString());
Log.v(TAG,mKnife.toString()); //this actually works !
}
}
更新:我写了一篇关于此功能的博客,以防有人需要帮助: http://j2emanue.blogspot.ca/
最佳答案
将 @Inject
放在构造函数上可以让 Dagger 检测到它。您可以在JSR 330中阅读更多相关信息。 .
关于android - Dagger 2 - 如何在没有组件注册的情况下使用 @Inject 标记类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406316/