我已经创建了一个组件,它只持续到活动的整个生命周期。我没有使用任何范围注释,只使用了该组件生命周期的快速示例如下所示:
public class MainActivity extends AppCompatActivity {
private final String TAG = getClass().getSimpleName();
@Inject
AlmondButter someAlmondButter;
@Inject
CashewSandwich sandwich;
SandwichComponent sandwichComponent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*create thte 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,sandwich.toString());
Log.v(TAG,someAlmondButter.toString());
}
@Override
protected void onDestroy() {
super.onDestroy();
//not necessary but it clearly shows the scope being tied to lifecycle of activity
sandwichComponent=null;
}}
我的组件中没有一个是通过模拟来限定范围的,而且工作正常。所以我搞不懂为什么有人建议创建范围标签,目的是什么?我将向您展示下面的组件,以供参考:
@Component(dependencies = ButterComponent.class, modules = SandwichModule.class)
public interface SandwichComponent {
CashewSandwich ProvideCashewSandwitch();
void inject (MainActivity mainactivity);
}下一个组成部分是:
@Component(modules={ButterModule.class})
public interface ButterComponent {
//these are for our whatever class depends on butter
AlmondButter ProvideAlmondButter();
CashewButter ProvideCashewButter();
}更新:对于任何需要帮助理解这些概念的人,我创建了一个博客这里。
发布于 2015-12-21 15:37:06
作用域管理同一类型的多个请求之间的实例创建。想象一下如果你有这个:
@Inject
AlmondButter someAlmondButter;
@Inject
AlmondButter otherAlmondButter;这将创建两个单独的AlmondButter实例。这是一个很小的例子,但希望它说明了一点:每次请求依赖项时,都会创建一个新的依赖项。
想象一下,现在您有两个不同的类,每个类都有一个字段@Inject AlmondButter sharedAlmondButter。如果希望它们具有相同的实例,作用域将为您处理这个问题。
类似地,对于您拥有的任何依赖项,您都可以注入一个Provider<T>,即@Inject Provider<AlmondButter> almondButterProvider。这允许您调用almondButterProvider.get()来检索新实例。如果您希望.get()返回的所有值都是同一个实例,那么作用域将完成相同的任务。
https://stackoverflow.com/questions/34397211
复制相似问题