Guice将对象注入类构造函数

时间:2019-01-27 02:53:41

标签: java dependency-injection guice

我刚刚开始寻找Guice的新项目。我有这样的东西

ConfigImpl类和Config接口

 interface Config{...}

 class ConfigImpl implements Config {
   private static final Map<> propMap;
   public ConfigImpl(Map<> propMap) {
     this.propMap = someProps;
   }
 }

我想出了注糖

public class MyInjector extends AbstractModule {
  protected void configure() {
    bind(Config.class).to(ConfigImpl.class)
  }
}

最后

public SomeClass {
  Config someConfig;
  Injector injector = Guice.createInjector(new MyInjector());
  someConfig = injector.getInstance(Config.class);          
}

现在我很困惑,因为我找不到将propMap传递到ConfigImpl类的方法。我想知道在Guice中执行此操作的正确方法。谢谢!

1 个答案:

答案 0 :(得分:2)

您应该从模块中注入propMaps

public class MyInjector extends AbstractModule {
  private final Map<String,String> mapProps;
  public MyInjector(Map<String,String> mapProps) {
    this.mapProps = mapProps;
  }
  protected void configure() {
    bind(Config.class).to(ConfigImpl.class).in(Scope.SINGLETON);         // You most than likely want this
    bind(new TypeLiteral<Map<String,String>>() {}).toInstance(mapProps); // binding for the map.
  }
}

并像这样使用它:

public class SomeClass {
  void doSomething() {
    Map<String,String> mapProps = ... ;
    Injector injector = Guice.createInjector(new MyInjector(mapProps));
    Config someConfig = injector.getInstance(Config.class);          
  }
}

此外,您应该修复ConfigImpl类:

class ConfigImpl implements Config {
  private final Map<String,String> propMap;
  @Inject                                         // mandatory since you use a non-default constructor
  public ConfigImpl(Map<String,String> propMap) { // add the generic type of the map
    this.propMap = propMap;
  }
}