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は常に bind を使用しContactsDetailViewImplます。しかし、私はそれがContactDetailViewImplXいくつかの条件下でバインドすることを望みます。

どうやってやるの?助けてください。

4

1 に答える 1

7

ある実装を注入し、別の実装を注入するように 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);
    }
}
于 2011-10-03T08:50:10.540 に答える