Google Guice的这两个绑定声明有什么区别? [英] what's the difference between these two binding declarations with Google Guice?

查看:88
本文介绍了Google Guice的这两个绑定声明有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别

bind(FooImpl.class).in(Scopes.SINGLETON);
bind(Foo.class).to(FooImpl.class);

bind(Foo.class).to(FooImpl.class).in(Scopes.SINGLETON);

使用Google Guice吗?

With Google Guice?

第二个声明在我正在处理的项目中的Singleton上创建两个实例. 此处引用

The second declaration create two instances on Singleton in a project I am working on. Reference here

推荐答案

参考中到Google Guice文档:

In reference to Google Guice documentation:

在链接绑定中,作用域适用于绑定源,而不适用于 结合目标.假设我们有一个Applebees类,它同时实现了 Bar和Grill界面.这些绑定允许两个实例 这种类型,一种用于酒吧,另一种用于烧烤:

In linked bindings, scopes apply to the binding source, not the binding target. Suppose we have a class Applebees that implements both Bar and Grill interfaces. These bindings allow for two instances of that type, one for Bars and another for Grills:

bind(Bar.class).to(Applebees.class).in(Singleton.class);
bind(Grill.class).to(Applebees.class).in(Singleton.class);

这是因为范围适用于绑定类型(Bar,Grill),而不是 满足绑定要求的类型(Applebees).只允许 要创建的单个实例,请在 该类的声明.或添加另一个绑定:

This is because the scopes apply to the bound type (Bar, Grill), not the type that satisfies that binding (Applebees). To allow only a single instance to be created, use a @Singleton annotation on the declaration for that class. Or add another binding:

bind(Applebees.class).in(Singleton.class);

因此,有可能在第二种方式中有两个FooImpl实例,但没有第一种方式来编写绑定.

So, It's possible to have two instances of FooImpl in the second way but not with the first way of writing the binding.

这篇关于Google Guice的这两个绑定声明有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆