开发者

How do I subtract a binding using a Guice module override?

开发者 https://www.devze.com 2022-12-30 09:56 出处:网络
So according to my testing, If you have something like: Module modA = new AbstractModule() { public void configure() {

So according to my testing, If you have something like:

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.

But what if you want to remove the binding for E in modB? I can't seem to find a way to do this without having to break the bind for E into a separate module. Is the开发者_如何学运维re a way?


The SPI can do this. Use Elements.getElements(modA, modB) to get a list of Element objects, representing your bindings. Iterate through that list and remove the binding whose key you'd like to remove. Then create a module from the filtered elements using Elements.getModule(). Putting it all together:

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);
}


Guice 4.0beta will return read only Element list. So I modify Jesse Wilson's code as the following. What you need do is provide the list of modules and subtract the target binding, which you want to replace.

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

Function

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;
    }));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消