Search code examples
guice

How to configure Guice to require explicit bindings for the whole application (for all modules)


In order to to use "explicit" bindings with Guice I can call binder().requireExplicitBindings() in my module implementations, e.g.

public class MyExampleModule extends AbstractModule {

    @Override
    protected void configure() {
        super.configure();
        binder().requireExplicitBindings();
        ...
    }
}

Regarding the Guice API, it looks for me like I need to do that in all my module implementations of my application.

Isn't there a way to configure this at one place for the whole application?

I'm using Guice 4.2.x


Solution

  • Binder configuration options like requireExplicitBindings() are global for everywhere that Binder is used. So unless you are doing something unusual with the Guice SPI, it applies to all bindings that form a part of the same Injector.

    Best practice is to only have a single Injector per application, so Binder options are already effectively global.

    For what it's worth, I think requireExplicitBindings() is overkill. Something like requireAtInjectOnConstructors() resolves the most egregious problems with implicit bindings, while still allowing for JSR-330 dependency injection based on annotated constructors, which can be a very convenient feature.