Overriding Binding in Guice

前端 未结 5 814
我在风中等你
我在风中等你 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 03:58

    Why not to use inheritance? You can override your specific bindings in overrideMe method, leaving shared implementations in configure method.

    public class DevModule implements Module {
        public void configure(Binder binder) {
            binder.bind(InterfaceA.class).to(TestDevImplA.class);
            overrideMe(binder);
        }
    
        protected void overrideMe(Binder binder){
            binder.bind(InterfaceC.class).to(ConcreteC.class);
        }
    };
    
    public class TestModule extends DevModule {
        @Override
        public void overrideMe(Binder binder) {
            binder.bind(InterfaceC.class).to(MockC.class);
        }
    }
    

    And finally create your injector this way:

    Guice.createInjector(new TestModule());
    

提交回复
热议问题