Overriding Binding in Guice

前端 未结 5 836
我在风中等你
我在风中等你 2020-11-28 03:37

I\'ve just started playing with Guice, and a use-case I can think of is that in a test I just want to override a single binding. I think I\'d like to use the rest of the pr

5条回答
  •  执笔经年
    2020-11-28 04:20

    This might not be the answer you're looking for, but if you're writing unit tests, you probably shouldn't be using an injector and rather be injecting mock or fake objects by hand.

    On the other hand, if you really want to replace a single binding, you could use Modules.override(..):

    public class ProductionModule implements Module {
        public void configure(Binder binder) {
            binder.bind(InterfaceA.class).to(ConcreteA.class);
            binder.bind(InterfaceB.class).to(ConcreteB.class);
            binder.bind(InterfaceC.class).to(ConcreteC.class);
        }
    }
    public class TestModule implements Module {
        public void configure(Binder binder) {
            binder.bind(InterfaceC.class).to(MockC.class);
        }
    }
    Guice.createInjector(Modules.override(new ProductionModule()).with(new TestModule()));
    

    See details here.

    But as the javadoc for Modules.overrides(..) recommends, you should design your modules in such a way that you don't need to override bindings. In the example you gave, you could accomplish that by moving the binding of InterfaceC to a separate module.

提交回复
热议问题