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

zer*_*021 14 java config constants guice

我想问一下有什么区别

bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
Run Code Online (Sandbox Code Playgroud)

bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);
Run Code Online (Sandbox Code Playgroud)

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

感谢和问候

马雷克

Col*_*inD 10

我认为使用的理由bindConstant()是:

  • 它要求您使用带注释的绑定.你做不到bindConstant().to(foo).由于与它绑定的类型是基元和Strings,因此无注释绑定对它们中的任何一个都没有意义.
  • 它需要较少的工作量,因为您不必指定类型(顺便说一下,bindConstant()绑定intInteger.class而不是Integer.TYPE,不确定是否重要).

我认为,Names.bindProperties不使用bindConstant,只是因为它的内部代码,多一些代码OK跳过作出有约束力的过程中一两步.在你自己的模块中,我只是使用bindConstant它,因为它很简单,更清晰.