我有以下代码
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();
这里CCD_ 1总是与CCD_ 2绑定。但我希望它在某些条件下与ContactDetailViewImplX
结合。
我该怎么做?请帮帮我。
您不能声明性地告诉Gin有时注入一个实现,有时注入另一个实现。不过,您可以使用Provider
或@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);
}
}