9

したがって、私のテストによると、次のようなものがある場合:

Module modA = new AbstractModule() {
    public void configure() {
        bind(A.class).to(AImpl.class);
        bind(C.class).to(ACImpl.class);
        bind(E.class).to(EImpl.class);
    }
}

Module modB = New AbstractModule() {
    public void configure() {
        bind(A.class).to(C.class);
        bind(D.class).to(DImpl.class);
    }
}

Guice.createInjector(Modules.overrides(modA, modB)); // gives me binding for A, C, E AND D with A overridden to A->C.

しかし、modB で E のバインドを削除したい場合はどうすればよいでしょうか? E のバインドを別のモジュールに分割することなく、これを行う方法を見つけることができないようです。方法はありますか?

4

2 に答える 2

13

SPIはこれを行うことができます。バインディングを表すオブジェクトElements.getElements(modA, modB)のリストを取得するために使用します。Elementそのリストを繰り返し処理し、キーを削除したいバインディングを削除します。次に、 を使用して、フィルタリングされた要素からモジュールを作成しますElements.getModule()。すべてを一緒に入れて:

public Module subtractBinding(Module module, Key<?> toSubtract) {
  List<Element> elements = Elements.getElements(module);

  for (Iterator<Element> i = elements.iterator(); i.hasNext(); ) {
    Element element = i.next();
    boolean remove = element.acceptVisitor(new DefaultElementVisitor<Boolean>() { 
      @Override public <T> Boolean visit(Binding<T> binding) { 
        return binding.getKey().equals(toSubtract);
      }
      @Override public Boolean visitOther(Element other) {
        return false;
      }
    }); 
    if (remove) {
      i.remove();
    }
  }

  return Elements.getModule(elements);
}
于 2010-05-18T05:00:43.117 に答える
4

Guice 4.0beta は読み取り専用の Element リストを返します。そこで、Jesse Wilson のコードを次のように変更します。必要なのは、モジュールのリストを提供し、置き換えたいターゲットバインディングを差し引くことです。

Injector injector = Guice.createInjector(new TestGuiceInjectionModule(), Utils.subtractBinding(new GuiceInjectionModule(),Key.get(IInfoQuery.class)));

関数

public static Module subtractBinding(Module module, Key<?> toSubtract) {
    List<Element> elements = Elements.getElements(module);

    return Elements.getModule(Collections2.filter(elements, input -> {
        if(input instanceof Binding)
        {
            return !((Binding) input).getKey().equals(toSubtract);
        }

        return true;
    }));
}
于 2014-02-06T11:53:58.447 に答える