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)加载我的所有配置属性; 在我的模块中,我发现它使用后者来绑定属性。
感谢和问候
马雷克
我认为使用bindConstant()
原因是:
- 它要求您使用带注释的绑定。 你不能将
bindConstant().to(foo)
。 由于与它绑定的类型是基元和String
,因此无注释绑定对它们中的任何一个都没有意义。 - 它需要更少的工作,因为您不必指定类型(顺便说一下,
bindConstant()
将int
绑定到Integer.class
而不是Integer.TYPE
,不确定是否重要)。
我认为Names.bindProperties
不使用bindConstant
只是因为它是内部代码而且在进行绑定的过程中可以跳过一两步的代码。 在你自己的模块中,我只使用bindConstant
因为它简单明了。
bindConstant()
的好处是能够设置不同的原语,因为Guice本身内部有预定义的TypeConverter
实例。
以下面的绑定定义为例:
bindContant().annotatedWith(@Names.named("c")).to("30");
然后在你想要注射的类中:
@Inject @Named("c") int value;
Guice会将绑定的String
转换为int
。 如果不能,就会这样说。
bindConstant()
的好处是可以发生的类型转换。 显式绑定int
并不能给你带来奢侈。