3

我有以下代码

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在某些条件下绑定。

我怎样才能做到这一点?请帮助我。

4

1 回答 1

7

您不能以声明方式告诉 Gin 有时注入一个实现,而在其他时候注入另一个实现。不过,您可以使用 aProvider或 a@Provides方法来完成。

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);
    }
}
于 2011-10-03T08:50:10.540 回答