我想问一下,两者有什么不同?
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);和
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);我想在我的模块中使用Names.bindProperties(binder(),prop);加载我的所有配置属性,我发现它使用后者来绑定属性。
谢谢,致以问候
马雷克
发布于 2010-11-13 00:12:28
我认为使用bindConstant()的原因是:
bindConstant().to(foo)。由于您使用它绑定的类型是基元类型和String类型,因此无注释绑定对它们中的任何一个都不太可能有意义。bindConstant()将int绑定到Integer.class而不是Integer.TYPE,不确定这是否重要)。我认为Names.bindProperties不使用bindConstant仅仅是因为它是内部代码,在创建绑定的过程中跳过一两步代码是可以的。在您自己的模块中,我只使用bindConstant,因为它更简单、更清晰。
发布于 2010-11-13 13:56:28
bindConstant()的好处是能够设置不同的原语,这是因为Guice本身中有预定义的TypeConverter实例。
以以下绑定定义为例:
bindContant().annotatedWith(@Names.named("c")).to("30");
然后在你想要注入的类中:
@Inject @Named("c") int value;
Guice将为您将绑定的String转换为int。如果做不到,它就会这么说。
bindConstant()的好处是可以进行类型转换。显式绑定int不会给您带来这种奢侈。
https://stackoverflow.com/questions/4165506
复制相似问题