Prerequisite
For Injecting dependency using guice, you should first know what is Dependency Injection. Please go through this article to understand Dependency Injection.
Introduction
Now that we know what is Dependency Injection, we can use it in our code. With dependency injection, objects accept dependencies in their constructors. To construct an object, you need first to build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph.
Here guice comes into the picture. It can build the object graph for you and all you have to is use those dependencies in your code and need not worry about how and where to get these dependencies.
Guice in Action
Guice controls Dependency Injection by Guice bindings.These bindings are used by guice to map object types to their actual implementations. All the bindings are defined in a module.
Let’s create a small application to better understand this. It is a simple application which tells user which vehicle being used for test drive.
Interface for vehicle
Bike implementation of vehicle
Car implementation of vehicle.
Module containing guice bindings.
Notice Vehicle class is bound to Bike implementation in module.
Now lets create class VehicleShopping with vehicle as dependency.
We need to create a guice injector for this dependency injection to work. An injector builds the graphs of objects that make up your application and tracks the dependencies for each type and uses bindings to inject them. Thus, the first step is to create an injector and then use the injector to get the objects.This method is to be called once during application startup.
Response after running application.
Here VehicleShopping class does not care which implementation is provided and all responsibility to get desired objects and their dependency resolved is handled by Guice.
Reference:
Clone the project from github
If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter: https://skillcaptain.substack.com
Leave a Reply