1

In my project I have a configuration file that lists the concrete implementation of an interface.

How do I configure my Guice module so that I can get an instance of the concrete class from the Type whenever the interface is injected?

interface A{}

class AImpl implements A{ @Inject public A(.....)}

class B {
  @Inject
  public B(A a) {}
}


class MyModule extends AbstractModule {
  ...
  @Provides
  public A getA(@ConfiguredClass String classname) {
     Class<A> aClass = (Class<A>) Class.forName(classname);
     // ???
     // this needs to be instantiated by Guice to fulfill AImpl's dependencies
     return aClass.newInstance();
  }
}

config:
class: my.package.AImpl
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
case nelson
  • 3,537
  • 3
  • 30
  • 37

1 Answers1

2

You could read in the configuration file during startup, convert it to a Map<Class, Class> and feed the mapping into the module and configure all the bindings like so:

public class MyModule extends AbstractMdoule{

    //interface -> concrete
    Map<Class, Class> implementsMap;
    ...
    public void configure() {
        for (Map.Entry<Class, Class> implEntry : implementsMap.entrySet()) {
            bind(implEntry.getKey()).to(implEntry.getValue());
        }
    }
}
John Ericksen
  • 10,995
  • 4
  • 45
  • 75
  • +1: And there's a related question at http://stackoverflow.com/questions/765680/why-theres-no-configuration-file-at-all-for-dependency-injection-with-google-gu – Don Roby May 10 '12 at 01:05