How to subtract binding using Guice module override?

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 cannot find a way to do this without breaking the binding for E in a separate module. Is there any way?

+4
source share
2 answers

+9
source

Guice 4.0beta will only return a list of Element elements. Therefore, I modify the Jesse Wilson code as follows. You need to provide a list of modules and subtract the binding to the target 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; })); } 
+2
source

Source: https://habr.com/ru/post/1310072/


All Articles