unj*_*nj2 4 java dependency-injection inversion-of-control guice robot-legs-problem
我是否需要创建一个新模块,并将接口绑定到不同的实现?
Chef newChef = Guice.createInjector(Stage.DEVELOPMENT, new Module() {
@Override
public void configure(Binder binder) {
binder.bind(FortuneService.class).to(FortuneServiceImpl.class);
}
}).getInstance(Chef.class);
Chef newChef2 = Guice.createInjector(Stage.DEVELOPMENT, new Module() {
@Override
public void configure(Binder binder) {
binder.bind(FortuneService.class).to(FortuneServiceImpl2.class);
}
}).getInstance(Chef.class);
Run Code Online (Sandbox Code Playgroud)
我无法触及Chef Class和Interfaces.我只是一个客户端在运行时绑定到Chef的FortuneService到不同的接口.
看起来像Guice FAQ中描述的Robot Legs部分."如何使用两个Leg对象创建一个机器人,左边的一个用LeftFoot注入,另一个用RightFoot注入." 但只有一个Leg类在两种情况下都被重用.
有一个PrivateModules解决方案.它使用两个独立的私有模块,一个是@Left,另一个是@Right.每个都有未注释的Foot.class和Leg.class的绑定,并为带注释的Leg.class公开绑定:
class LegModule extends PrivateModule {
private final Class<? extends Annotation> annotation;
LegModule(Class<? extends Annotation> annotation) {
this.annotation = annotation;
}
@Override protected void configure() {
bind(Leg.class).annotatedWith(annotation).to(Leg.class);
expose(Leg.class).annotatedWith(annotation);
bindFoot();
}
abstract void bindFoot();
}
Run Code Online (Sandbox Code Playgroud)
......并将它们粘合在一起:
public static void main(String[] args) {
Injector injector = Guice.createInjector(
new LegModule(Left.class) {
@Override void bindFoot() {
bind(Foot.class).toInstance(new Foot("leftie"));
}
},
new LegModule(Right.class) {
@Override void bindFoot() {
bind(Foot.class).toInstance(new Foot("righty"));
}
});
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5601 次 |
最近记录: |