Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guice

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 there a way?

like image 526
Y.H Wong Avatar asked May 18 '10 04:05

Y.H Wong


2 Answers

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);
}
like image 140
Jesse Wilson Avatar answered Sep 28 '22 05:09

Jesse Wilson


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;
    }));
}
like image 42
Shen liang Avatar answered Sep 28 '22 05:09

Shen liang