This blog has moved to Medium

Subscribe via email


MapBinder basics in Guice

Another less known feature in Google Guice is map binders. I haven’t seen a good basic map binder tutorial, so I wanted to share the little I learned about it (it is covered in the documentation, but it’s not necessarily the best intro material). Basically, is a way to collect bindings from several models into one central map. The idiom is having each module add bindings from its “knowledge domain”, and providing the entire collection as one unified map.

class SomeModule {
  protected void configure() {
     // Bind the value "Eve" to the key "Adam"
     MapBinder.newMapBinder(binder(), String.class, String.class)
       .addBinding("Adam").toInstance("Eve");
  }
}
 
class AnotherModule {
  protected void configure() {
     // Bind the value "Abel" to the key "Kane"
     MapBinder.newMapBinder(binder(), String.class, String.class)
       .addBinding("Kane").toInstance("Abel");
  }
}
 
class NeedsMap {
  @Inject
  NeedsMap(Map<String, String> biblicalNames) {
    // gets a map of all values bound in the relevant modules
  }
}
 
main() {
  NeedsMap needsMap = Guice.createInjector(new SomeModule(), new AnotherModule()).getInstance(NeedsMap.class);
}

Of course, the map can be specified using any types, not just String, and doesn’t have to bind to a specific instance, but can bind to a class. To use this, remember to depend on the proper Guice Extension (Maven guice-multibindings). The code is available on Github. Check out this questions for “when is this actually useful?