我有以下用例.
class ServiceClient { Object val; @Inject public ServiceClient(MyInterface ob){ this.val = ob.getVal(); } } class UserClass1{ @Inject UserClass1(ServiceClient sc){ } } class UserClass2{ @Inject UserClass2(ServiceClient sc){ } }
现在,在用户类中注入服务客户端时,我希望在ServiceClient构造函数类中注入不同的MyInterface实现.
我怎样才能在谷歌Guice中实现这一目标?
您可以使用@Named
注释来区分不同的实现:
class UserClass1 { @Inject UserClass1(@Named("Service1") ServiceClient sc) { } } class UserClass2 { @Inject UserClass2(@Named("Service2") ServiceClient sc) { } } class MyModule extends AbstractModule { @Override protected void configure() { bind(ServiceClient.class).annotatedWith(Names.named("Service1")).toInstance(new ServiceClient(new AA())); bind(ServiceClient.class).annotatedWith(Names.named("Service2")).toInstance(new ServiceClient(new AB())); } }