Android 匕首2-在没有组件注册的情况下,用@Inject标记类构造函数是如何工作的
我已经用两个部件安装了匕首。一个组件是另一个重要组件的子组件。一切正常。但后来我随机地想尝试构造函数注入,所以我创建了一个随机类,并用注入注释标记了它的构造函数。令我惊讶的是,当我想注入这个类时,它还能工作吗?我的组件对此一无所知。我没有在我的组件接口中写过关于这个类的内容。它只是一个随机类,有一个用@Inject注释的构造函数。这是怎么回事?以下是随机类:Android 匕首2-在没有组件注册的情况下,用@Inject标记类构造函数是如何工作的,android,dependency-injection,dagger-2,Android,Dependency Injection,Dagger 2,我已经用两个部件安装了匕首。一个组件是另一个重要组件的子组件。一切正常。但后来我随机地想尝试构造函数注入,所以我创建了一个随机类,并用注入注释标记了它的构造函数。令我惊讶的是,当我想注入这个类时,它还能工作吗?我的组件对此一无所知。我没有在我的组件接口中写过关于这个类的内容。它只是一个随机类,有一个用@Inject注释的构造函数。这是怎么回事?以下是随机类: public class Knife { @Inject public Knife(){ System.out.println(
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 !
}
}
更新:我写了一篇关于此功能的博客,以防任何人需要帮助:
将
@Inject
放置在构造函数上可以检测到匕首。您可以在中了解更多信息。如果提供的是非作用域,那么我假设您可以在类中添加一个作用域:`@Singleton class-Knife{@Inject-public-Knife(){}}`我尝试了这个方法,效果很好。向类中添加一个作用域使其与作用域一样有效,谢谢。