简体   繁体   中英

Guice inject an object to a class constructor

I just started looking at Guice for a new project. I have something like this

the ConfigImpl class ans Config interface

 interface Config{...}

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

Guice injection I came up with

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

and finally

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

Now I am very confused as I can't find a way to pass propMap into ConfigImpl class. I'd like to know the proper way of doing it in Guice. Thanks!

You should inject propMaps from your module:

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.
  }
}

And use it like this:

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

Also, you should fix your ConfigImpl class:

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM