Guice:使用@Named 注入映射绑定
Guice: Injecting map binding with @Named
我想要以下注入模型。 Guice 可以做到这一点吗?
模块:
protected void configure() {
MapBinder<String, IService> mapBinder = MapBinder.newMapBinder(binder(), String.class, IService.class);
mapBinder.addBinding("keyA").to(IServiceA.class);
mapBinder.addBinding("keyB").to(IserviceB.class);
}
Class:
class SomeClass {
private final IService service;
@Inject
SomeClass(@Named("KeyA") final IService serviceInstance) {
this.service = serviceInstance;
}
}
@Named
注释必须添加到方法的参数上。
class SomeClass {
private final IService service;
@Inject
SomeClass(@Named("KeyA") final IService serviceInstance) {
this.service = serviceInstance;
}
}
https://github.com/google/guice/wiki/Injections#method-injection
这不是地图活页夹的用途。
在您的示例中,绑定注释将是可行的方法:
https://github.com/google/guice/wiki/BindingAnnotations
protected void configure() {
bind(IServiceA.class).annotatedWith(Names.named("keyA"));
bind(IServiceB.class).annotatedWith(Names.named("keyB"));
}
我想要以下注入模型。 Guice 可以做到这一点吗?
模块:
protected void configure() {
MapBinder<String, IService> mapBinder = MapBinder.newMapBinder(binder(), String.class, IService.class);
mapBinder.addBinding("keyA").to(IServiceA.class);
mapBinder.addBinding("keyB").to(IserviceB.class);
}
Class:
class SomeClass {
private final IService service;
@Inject
SomeClass(@Named("KeyA") final IService serviceInstance) {
this.service = serviceInstance;
}
}
@Named
注释必须添加到方法的参数上。
class SomeClass {
private final IService service;
@Inject
SomeClass(@Named("KeyA") final IService serviceInstance) {
this.service = serviceInstance;
}
}
https://github.com/google/guice/wiki/Injections#method-injection
这不是地图活页夹的用途。 在您的示例中,绑定注释将是可行的方法: https://github.com/google/guice/wiki/BindingAnnotations
protected void configure() {
bind(IServiceA.class).annotatedWith(Names.named("keyA"));
bind(IServiceB.class).annotatedWith(Names.named("keyB"));
}