我想问一下有什么区别
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
和
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);
我想用 Names.bindProperties(binder(), prop); 加载我所有的配置属性在我的模块中,我发现它使用后一个来绑定(bind)属性。
谢谢,问候
马立克
最佳答案
我认为使用 bindConstant()
的原因是:
- 它要求您使用带注释的绑定(bind)。你不能做
bindConstant().to(foo)
。由于您与之绑定(bind)的类型是原始类型和String
,因此无注释绑定(bind)不太可能对它们中的任何一个都有意义。 - 它需要更少的努力,因为您不必指定类型(顺便说一下,
bindConstant()
将int
绑定(bind)到Integer.class
而不是Integer.TYPE
,不确定这是否重要)。
我认为 Names.bindProperties
不使用 bindConstant
只是因为它是内部代码,多一点代码就可以跳过制作过程中的一两步一个绑定(bind)。在您自己的模块中,我只使用 bindConstant
,因为它既简单又清晰。
关于java - Guice:Binder#bindConstant() 和 Binder#bind() 之间的区别 ... toInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4165506/