Java Guice:Binder#bindcontent()和Binder#bind()之间的区别。。。指示灯
我想问一下两者之间的区别是什么Java Guice:Binder#bindcontent()和Binder#bind()之间的区别。。。指示灯,java,constants,config,guice,Java,Constants,Config,Guice,我想问一下两者之间的区别是什么 bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60); 及 我想用name.bindProperties(binder(),prop)加载所有配置属性;在我的模块中,我发现它将后者用于绑定属性 谢谢,问候 Marek我认为使用bindConstant()的原因是: 它要求您使用带注释的绑定。您不能对(foo)执行bindConstant()。由于使用它绑定的类型是原语和Str
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
及
我想用name.bindProperties(binder(),prop)加载所有配置属性;在我的模块中,我发现它将后者用于绑定属性
谢谢,问候
Marek我认为使用
bindConstant()
的原因是:
- 它要求您使用带注释的绑定。您不能对(foo)执行
bindConstant()。由于使用它绑定的类型是原语和
s,因此不太可能使用无注释绑定String
- 由于您不必指定类型,因此需要更少的工作(顺便说一句,
将bindcontent()
绑定到int
而不是Integer.class
,不确定这是否重要)Integer.type
Names.bindProperties
不使用bindcontent
仅仅因为它是内部代码,在创建绑定的过程中跳过一两步就可以了。在您自己的模块中,我只使用bindcontent
,因为它简单明了。bindcontent()
的好处是能够设置不同的原语,因为Guice本身中预定义了TypeConverter
实例
以以下绑定定义为例:
bindContant().annotatedWith(@Names.named(“c”))to(“30”)代码>
然后在需要注入的类中:
@Inject@Named(“c”)int值代码>
Guice将为您将绑定的字符串
转换为int
。如果不能,它会这样说
bindcontent()
的好处是可以进行类型转换。显式绑定一个int
并不会给你带来那种奢侈。+1只是想做一些类似的事情。正如bindProperties()
如何不使用bindcontent()
所证明的那样,这并不完全正确。使用bind(String.class)。toInstance(“30”)
工作正常,允许将绑定转换为int
,就像bindConstant()
一样。我不相信TypeConverter
的东西会关心你是如何开始绑定的。事实上,正如我在我的文章中提到的,Names.bindProperties不使用bindcontent,但是类型转换会发生(例如,主机和端口是String和int,它们都是正确注入的类型-没有转换错误)没错,没有。不过,从用户的角度来看,应该考虑到这一点,因为这是Guice的内部逻辑。
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);