Guice:Binder#bindConstant() 和 Binder#bind() 之间的区别 ... toInstance
我想问一下有什么区别
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
,
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);
我想用 Names.bindProperties(binder(), prop); 加载所有配置属性;在我的模块中,我发现它使用后一个来绑定属性。
谢谢,问候
马雷克
I would like to ask what's the difference between
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
and
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);
I would like to load all my configuration properties with Names.bindProperties(binder(), prop); in my module and I discovered that it uses the latter one for binding properties.
Thanks, regards
Marek
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为使用
bindConstant()
的原因是:bindConstant().to(foo)
。由于您绑定的类型是基元和 String,因此无注释绑定对它们中的任何一个都不太有意义。bindConstant()
将int
绑定到Integer.class
而不是Integer.TYPE
,不确定这是否重要)。我认为
Names.bindProperties
不使用bindConstant
只是因为它是内部代码,并且在进行绑定的过程中跳过一两个步骤就可以多一点代码。在您自己的模块中,我只使用bindConstant
因为它简单且更清晰。I think reasons to use
bindConstant()
are:bindConstant().to(foo)
. Since the types you bind with it are primitives andString
s, it's unlikely that an annotation-less binding would make sense for any of them.bindConstant()
binds anint
toInteger.class
rather thanInteger.TYPE
, not sure if that matters).I think
Names.bindProperties
doesn't usebindConstant
just because it's internal code and a little more code is OK to skip a step or two in the process of making a binding. In your own modules, I'd just usebindConstant
because it's easy and more clear.bindConstant()
的好处是能够设置不同的原语,因为 Guice 本身预定义了TypeConverter
实例。以下面的绑定定义为例:
bindContant().annotatedWith(@Names.named("c")).to("30");
然后在你想要注入的类中:
@Inject @Named("c") int value;
Guice 会将绑定的
String
转换为int
。如果不能的话,它会这样说。bindConstant()
的好处是可以发生类型转换。显式绑定int
并不会给您带来那种奢侈。bindConstant()
has the benefit of being able to set different primitives because of predefinedTypeConverter
instances within Guice itself.Take the following binding definition as an example:
bindContant().annotatedWith(@Names.named("c")).to("30");
Then in a class where you want the injection:
@Inject @Named("c") int value;
Guice will convert the bound
String
into anint
for you. If it cannot, it will say so.The benefit of
bindConstant()
is the type conversion that can happen. Explicitly binding anint
does not give you that luxury.