Override guice bindings

Guice natively support bindings override with Modules.override() api. This is mostly useful in tests, when some bindings could be overridden with mocks. But it could also be used in real application in order to "workaround" some 3rd party module behaviour.

Guicey provides special support for overridings registration.

You need 2 modules: one with original binding and another with binding override.

For example, suppose you want to replace ServiceX binding from:

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ServiceX.class).to(ServiceXImpl.class);        
    }
}

Generally have few options:

  • If it implement interface, implement your own service and bind as bind(ServiceX.class).to(MyServiceXImpl.class)
  • If service is a class, you can modify its behaviour with extended class bind(ServiceX.class).to(MyServiceXExt.class)
  • Or you can simply register some mock instance bind(ServiceX.class).toInstance(myMockInstance)

Here assume that ServiceX is interface, so simply register different implementation:

public class MyOverridingModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(ServiceX.class).to(CustomServiceXImpl.class);        
    }
}

Now register overriding:

GuiceBundle.builder()
    .modules(new MyModule())
    .modulesOverride(new MyOverridingModule())  
    .build()  

And everywhere in code @Inject ServiceX service; will receive CustomServiceXImpl (instead of ServiceXImpl)

Tip

Sometimes it may be simpler to disable existing module and register new module with modified bindings instead of overrides (for example with a hooks)

Note

Overriding module could contain additional bindings - they would be also available in the resulted injector. (binding from overriding module either overrides existing binding or simply added as new binding)