2
我的匕首已经设置了两个组件。一个组件是另一个重要组件的子组件。一切正常。但后来我随机想尝试构造函数注入,所以我创建了一个随机类,并用Inject注解标记了它的构造函数,当我想注入这个类时,我感到惊讶。我的组件对此一无所知。我没有写过关于这个类的组件接口。它只是一个随机类,它有一个用@Inject注解的构造函数。这是如何工作的?这里是随机类:Dagger 2 - 如何使用@Inject标记类构造函数而不使用组件注册工作
public class Knife {
@Inject
public Knife(){
System.out.println("a spreading knife has been created");
};
}
,这里是如何调用注入我的课,如果该事项:
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/
请问可以提供无范围的话,我认为 – j2emanue
您可以添加一个范围到类: ' @Singleton 类刀{ @Inject 公刀(){}} ' 我 – rdshapiro
尝试这样有用。向课堂中添加一个范围使其与活动范围一样长,谢谢。 – j2emanue