So far, we have worked with directly injecting dependencies. Yet, there are a few cases where injecting direct dependencies may not be an appropriate choice. Let's discuss such scenarios, and figure out how a Factory style Provider
class provides a better way to inject dependencies.
Guice provides an instance by invoking a suitable constructor. Whenever dependency injection happens, Guice requires all the instances be ready upfront to complete the wiring process. This is, however, undesirable in various situations. Consider FlightSupplier. Every time you require an instance of Client, all the dependencies would be wired to CSVSupplier. But effectively speaking, until a processRequest()
invocation is made on FlightEngine's instance, CSVSupplier doesn't come into picture.
Following are certain drawbacks of early instantiation:
Late initialization may be required. Based on the client request, it would be unnecessary to parse all the
.csv
files...