我是 Java 初学者和 IoC。东西怎么做:
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
}
else{
return new BarImpl(); //an implemantation of Bar interface
}
}
}
在 Guice 示例中以 IoC 方式?
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??
}
}
我应该如何配置我的注射器?
@Override
protected void configure() {
bind(Bar.class).to(BarImpl.class);
//and what else??
}