在 Guice 中使用 Mapbinder 在模块中使用注入

Using Inject in a Module using Mapbinder in Guice

我正在使用 Guice MapBinder 将接口的不同实现绑定到特定键。问题是,我需要在这些绑定中注入一些依赖项。我认为这是不可能的,因为我需要通过这样做来初始化模块:

Guice.createInjector(new SomeModule());

有可能吗?

编辑:更完整的示例:

接口:

public interface SomeInterface {
  String getName();
}

实施:

public class SomeImplementation imlements SomeInterface{
   @Inject
   public SomeImplementation(SomeDependency someDep){
       //this needs to be injected
   }

   @Override
   public String getName(){
      //getNameFromDependency
   }
}

模块:

public class SomeModule extends AbstractModule {

 @Override
 protected void configure() {
   MapBinder<String, SecureToken> binder = MapBinder.newMapBinder(binder(), String.class, SomeInterface.class);

    //bind stuff
   }
}

编辑2: 问题是,我使用反射来获取接口的所有实现。要调用方法 "getName",我需要调用 newInstance。这似乎是问题所在...... :-/

protected void configure() {
    MapBinder<String, SomeInterface> binder = MapBinder.newMapBinder(binder(), String.class, SecureToken.class);
    try {
      Set<Class<? extends SomeInterface>> subTypes = reflections.getSubTypesOf(SecureToken.class);
      for (Class<? extends SecureToken> clazz : subTypes) {
        SomeInterface someInterface = clazz.newInstance();
        String name = someInterface.getName();
        binder.addBinding(name).toInstance(someInterface);
      }
    } catch (IllegalAccessException | InstantiationException e) {
      e.printStackTrace();
    }
  }

你不再是"binding",你有 (IMO) 工厂。所以你应该这样公开它。 注意:您可以注入注入器,这(对于工厂)是一件非常好的事情。