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()。由于使用它绑定的类型是原语和
    String
    s,因此不太可能使用无注释绑定
  • 由于您不必指定类型,因此需要更少的工作(顺便说一句,
    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);