Let's say I have a Guice module ProdModule that I would like to depend on other GuiceModules, ProdDbModule and ProdPubSubModule. How would I implement ProdModule's configure()?
Note that the only Guice-specific code in the above is the @Inject annotation. This annotation marks an injection point. Guice will attempt to reconcile the dependencies implied by the annotated constructor, method, or field.
Guice Basic Bindings. Binding is to Guice as wiring is to Spring. With bindings, we define how Guice is going to inject dependencies into a class. This module implementation specifies that an instance of DefaultCommunicatorImpl is to be injected wherever a Communicator variable is found.
Guice (pronounced 'juice') is a lightweight dependency injection framework for Java 8 and above, brought to you by Google.
@Target(value={METHOD,CONSTRUCTOR,FIELD}) @Retention(value=RUNTIME) @Documented public @interface Inject. Annotates members of your implementation class (constructors, methods and fields) into which the Injector should inject values. The Injector fulfills injection requests for: Every instance it constructs.
You would install your other modules
protected void configure(){ install(new ProdDbModule()); install(new ProdPubSubModule()); // etc. }
While it can be convenient to use install
, you don't even need to install
the other modules as long as you provide all the necessary modules when you create your Injector
:
Injector injector = Guice.createInjector(new ProdDbModule(), new ProdPubSubModule(), new ProdModule());
This can give you more flexibility to change out just one of these modules in your entry point class without needing to modify ProdModule
itself. You can also indicate in a module what bindings it requires other modules to provide using the requireBinding
methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With