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 {
    protected void configure() {

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 {
    protected void configure() {

Now register overriding:

    .modules(new MyModule())
    .modulesOverride(new MyOverridingModule())  

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


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


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)