Guice:在Single Class构造函数中注入多个实现

sha*_*anu 3 java binding dependency-injection guice

我有以下用例.

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){
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,在用户类中注入服务客户端时,我希望在ServiceClient构造函数类中注入不同的MyInterface实现.

我怎样才能在谷歌Guice中实现这一目标?

nog*_*ard 5

您可以使用@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()));
    }
}
Run Code Online (Sandbox Code Playgroud)