In this tutorial we will create an
Injector out of multiple DI modules.
Then we will use the
Injector to create an instance of some service.
We will use annotation-based approach for defining modules as it is more readable.
For the tutorial we will need 2 helper classes. A
DataSource class that represents source of some data and a
Service class which uses data retrieved from a data source for some processing.
@Inject annotation on the
DataSource constructor. It will be explained later.
We will define two different modules: one for the configuration and another one for the service itself.
ConfigModule provides both the address for the
DataSource as well as a database name.
ServiceModule only provides the
Service itself that requires
DataSource to be instantiated.
Injector is creted out of two previously defined modules. After that, an instance of
Service is required from the injector.
DataSource to be instantiated, but we have not provided
DataSource explicitly in any of the modules.
Thanks to the
@Inject annotation on
DataSource's constructor, injector injected required dependencies and instantiated the
The output of
service.process() call is: