GWT-GIN多重实现?

时间:2011-10-03 04:56:37

标签: gwt dependency-injection gin

我有以下代码

public class AppGinModule extends AbstractGinModule{
    @Override
    protected void configure() {
        bind(ContactListView.class).to(ContactListViewImpl.class);
        bind(ContactDetailView.class).to(ContactDetailViewImpl.class);
    }
}

@GinModules(AppGinModule.class) 
public interface AppInjector extends Ginjector{
    ContactDetailView getContactDetailView();
    ContactListView getContactListView();
}

在我的切入点

AppInjector appInjector = GWT.create(AppGinModule.class);
appInjector.getContactDetailsView();

此处ContactDetailView始终与ContactsDetailViewImpl绑定。但我想在某些条件下与ContactDetailViewImplX绑定。

我该怎么做?请帮助我。

1 个答案:

答案 0 :(得分:7)

你不能以声明的方式告诉Gin有时会注入一个实现,而有时则注入另一个实现。您可以使用Provider@Provides method来执行此操作。

Provider示例:

public class MyProvider implements Provider<MyThing> {
    private final UserInfo userInfo;
    private final ThingFactory thingFactory;

    @Inject
    public MyProvider(UserInfo userInfo, ThingFactory thingFactory) {
        this.userInfo = userInfo;
        this.thingFactory = thingFactory;
    }

    public MyThing get() {
        //Return a different implementation for different users
        return thingFactory.getThingFor(userInfo);
    }   
}

public class MyModule extends AbstractGinModule {
  @Override
  protected void configure() {
      //other bindings here...

      bind(MyThing.class).toProvider(MyProvider.class);
  }
}

@Provides示例:

public class MyModule extends AbstractGinModule {
    @Override
    protected void configure() {
        //other bindings here...
    }

    @Provides
    MyThing getMyThing(UserInfo userInfo, ThingFactory thingFactory) {
        //Return a different implementation for different users
        return thingFactory.getThingFor(userInfo);
    }
}