About Guice

Guice is a dependency injection framework for Java. For more information, see https://github.com/google/guice.

Introduction

Prior to the 4.0 release of Guice, creating a Set or Map of bindings to inject was accomplished using a Multibinder (JavaDoc) as follows:

The limitation to this approach include having to add all of the bindings to the multibinder within one Guice module (or having to pass around the Multibinder between Guice modules at configure-time).

With Guice 4.0, a new method has been added to creating a Set or Map of bindings: the @ProvidesIntoSet (JavaDoc) and @ProvidesIntoMap (JavaDoc) annotations along with the MultibindingsScanner (JavaDoc). These have simplified the multibinding process as follows:

Using the annotations and the MultibindingsScanner allows for the bindings to be separated out into multiple modules without having to pass around or explicitly create a Multibinder. Existing examples (such as the Guice unit tests, ProvidesIntoTest.java) illustrate how to use this methodology with instances created at configure-time rather than run-time. This becomes complicated when those instances have dependencies that are created and bound elsewhere. The example below illustrates how to use these annotations without requiring configure-time instantiation.

Multibinding with @Provides and @ProvidesIntoSet (or @ProvidesIntoMap)

Rather than instantiating at configure-time with @ProvidesIntoSet, we can use a @Provides annotated method to construct the class after configuring the Guice-modules, and after all of the required dependencies have been bound.

With the sample above, we are relying on Guice to configure all modules and resolve all dependencies before our DemoPlugin implementations are instantiated. This allows us to create our Multibinder without having to have all of the dependencies instantiated before binding.

Sample Project

The following code snippets put this all together for a sample project.

Testing the Sample Code

We can instantiate a Guice injector for the DemoGuiceModule to validate our Multibinder:

Output

Plugin Count: 2
Hello from the Blue plugin.
Hello from the Red plugin.

Pin It on Pinterest

Share This
%d bloggers like this: