从 Guice 中的 MapBinder 获取实现

Get implementations off a MapBinder in Guice

基本上我想了解 MapBinder 的工作原理。例如,我尝试搜索但找不到令我满意的。在我提问之前,这是我的一些设置。

public class MyModule extends AbstractModule {

  @Override
  protected void configure() {
    MapBinder<String, MyInterface> binder = MapBinder.newMapBinder(.....);
    binder.addBinding("one", One.class);
    binder.addBinding("two", Two.class);
  }

}

public class EntryPoint {
  @Inject
  Map<String, MyInterface> myMap;

  public void start() {
    Injector injector = Guice.createInjector(new MyModule());
    Two two = myMap.get("two");
    //Use two here.
  }
}

如何将绑定注入 myMap?感觉自己用的不对

你不会让你的 EntryPoint 被注射到任何地方。你想做

EntryPoint ep = injector.getInstance(EntryPoint.class);

或者如果那行不通,

injector.injectMembers(this);

来自 EntryPoint.