Guice: Difference between Binder#bindConstant() an

2019-03-24 13:35发布

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.

Thanks, regards

Marek

2条回答
仙女界的扛把子
2楼-- · 2019-03-24 13:47

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

Take the following binding definition as an example:

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

Then in a class where you want the injection:

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

Guice will convert the bound String into an int for you. If it cannot, it will say so.

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

查看更多
Deceive 欺骗
3楼-- · 2019-03-24 13:50

I think reasons to use bindConstant() are:

  • 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 int to Integer.class rather than Integer.TYPE, not sure if that matters).

I think Names.bindProperties doesn't use bindConstant just 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 bindConstant because it's easy and more clear.

查看更多
登录 后发表回答