java Guice:Binder#bindConstant() 和 Binder#bind() 之间的区别...... toInstance

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4165506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:07:58  来源:igfitidea点击:

Guice: Difference between Binder#bindConstant() and Binder#bind() ... toInstance

javaconstantsconfigguice

提问by zeratul021

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.

我想用 Names.bindProperties(binder(), prop) 加载我所有的配置属性;在我的模块中,我发现它使用后一个来绑定属性。

Thanks, regards

感谢和问候

Marek

马立克

采纳答案by ColinD

I think reasons to use bindConstant()are:

我认为使用的原因bindConstant()是:

  • It requires that you use an annotated binding. You can't do bindConstant().to(foo). Since the types you bind with it are primitives and Strings, it's unlikely that an annotation-less binding would make sense for any of them.
  • It requires less effort since you don't have to specify the type (by the way, bindConstant()binds an intto Integer.classrather than Integer.TYPE, not sure if that matters).
  • 它要求您使用带注释的绑定。你不能做bindConstant().to(foo)。由于与它绑定的类型是原始类型和Strings,因此无注释绑定不太可能对它们中的任何一个有意义。
  • 它需要较少的努力,因为您不必指定类型(顺便说一下,bindConstant()绑定intInteger.class而不是Integer.TYPE,不确定这是否重要)。

I think Names.bindPropertiesdoesn't use bindConstantjust 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 use bindConstantbecause it's easy and more clear.

我认为Names.bindProperties不使用bindConstant仅仅因为它是内部代码,多一点代码就可以跳过绑定过程中的一两个步骤。在您自己的模块中,我只是使用bindConstant它,因为它更简单、更清晰。

回答by gpampara

bindConstant()has the benefit of being able to set different primitives because of predefined TypeConverterinstances within Guice itself.

bindConstant()由于TypeConverterGuice 本身内有预定义的实例,因此能够设置不同的原语。

Take the following binding definition as an example:

以如下绑定定义为例:

bindContant().annotatedWith(@Names.named("c")).to("30");

bindContant().annotatedWith(@Names.named("c")).to("30");

Then in a class where you want the injection:

然后在您想要注入的类中:

@Inject @Named("c") int value;

@Inject @Named("c") int value;

Guice will convert the bound Stringinto an intfor you. If it cannot, it will say so.

Guice 将为您将边界String转换为一个int。如果它不能,它会这样说。

The benefit of bindConstant()is the type conversion that can happen. Explicitly binding an intdoes not give you that luxury.

的好处bindConstant()是可以发生类型转换。显式绑定 anint并没有给你那么奢侈。