What is the use of requireBinding?

Viewed 2066

I am relatively new to Guice and trying to understand the usage of requireBinding and when/why to use it.

As per my understanding, while creating an injector Guice goes through the code of configure() method of all the modules and builds a dependency graph.

If Guice builds the dependency graph in itself then why does a module need to add a requireBinding? As long as I could understand the usage of requireBinding is to add an explicit dependency on a class which guice's dependency graph seems to be doing anyway.

I would like to understand that when should we use requireBinding and what is the impact of not using it in a module.

I have read Guice's official documentation and search on all the existing questions on Stackoverflow/any other blog but couldn't find a satisfying answer to the above question.

Adding to the original question.

Looking at the Source code of the AbstractModule the implementation looks like

protected void requireBinding(Key<?> key) {
    this.binder().getProvider(key);
}

protected void requireBinding(Class<?> type) {
    this.binder().getProvider(type);
}

Which you would assume will not have any side effect as it's a "get" call. But on the other hand looking it the binder itself it adds some element to a list of elements of type ProviderLookup

public <T> Provider<T> getProvider(Dependency<T> dependency) {
        ProviderLookup<T> element = new ProviderLookup(this.getElementSource(), dependency);
        this.elements.add(element);
        return element.getProvider();
    }
1 Answers

I've always though of requireBinding() as a contract for the Module.

You are correct that the graph would eventually fail when you call #get() or tried to inject an object that depends on the binding. However, I believe requireBinding will cause a failure when the Injector is created vs when the object is created (via the injector). When I was at Google, it functioned more as a contract, less as something with consequential behavior.

Related