开发者

IoC problem with multi binding

I'm Java beginner and IoC as well. How to do stuff:


public class Foo{

    //private Bar bar; //Bar is an interface private int var; public Foo(){ } public void setVar(int var){
      this.var = var;
    } public Bar getBar(){
      if(var==1){
        return new BarImpl1(); //an implemantation of Bar interface
      }
      else if(var==2){
        return new BarImpl2(); //an implemantation of Bar interface
      }
    }
}

in IoC way on Guice example?


public class Foo{

    private Bar bar; //Bar is an interface private int var; @Inject public Foo(Bar bar){
      this.bar = bar;
    } public void setVar(int var){
      this.var = var;
    } public Bar getBar(){
      return bar; // or what else??
    }
}

How should I configure my injector?


@Override 
protected void configure() {
    bind(Bar.class).to(BarImpl.class);

    //and what else??

}


I'm going to assume that var is a code that is determined at runtime based on data, user input, etc. and a single instance of Foo must be able to return different implementations of Bar depending on that code (it's a dynamic Bar factory).

In that case, what you probably want to do is use MapBinder from the Multibinding extension.

You'd probably do something like this:

MapBinder<Integer, Bar> mapbinder
     = MapBinder.newMapBinder(binder(), Integer.class, Bar.class);
mapbinder.addBinding(1).to(BarImpl1.class);
mapbinder.addBinding(2).to(BarImpl2.class);

bind(Bar.class).to(BarImpl.class); // the fallback

Then Foo might look like:

public class Foo {
   private final Provider<Bar> defaultProvider;
   private final Map<Integer, Provider<Bar>> barTypeMap;

   private int var = -1;

   @Inject public Foo(Provider<Bar> defaultProvider, 
                      Map<Integer, Provider<Bar>> barTypeMap) {
     this.defaultProvider = defaultProvider;
     this.barTypeMap = barTypeMap;
   }

   public void setVar(int var) { ... }

   public Bar getBar() {
     if(barTypeMap.containsKey(var)) {
       return barTypeMap.get(var).get();
     }

     return defaultProvider.get();
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜