×
☰ See All Chapters

What is Spring Dependency Injection

Dependency Injection - DI means, instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation. If you want to call any business functionality you need to create instance for the required component and sometimes you need to look up registry for some other component. To eliminate this spring offers Inversion of Control (IOC) where spring container is responsible to create and inject the required instances. Spring container is responsible to create the bean instances and also responsible to associate the dependencies. The main advantage of DI is loose coupling.

If resources/application is spending time to search and gather its dependent values then it is called dependency lookup.

In dependency lookup resources/application pulls the values from other resources.

Ex: Student gathers his course materials (dependent value) from institute by requesting for it. (Gathering explicitly)

If underlying container or framework or server is dynamically assigning values to resources/applications then it is called as dependency injection/Inversion of control.

In dependency injection underlying container or framework or server dynamically pushes dependent values to resources/applications.

Ex: If student is getting course materials automatically the moment he registered for course.

In spring values required for a spring resources/applications will be assigned by spring framework or spring containers dynamically.

You might hear the terms Inversion of Control and Dependency Injection used interchangeably, but in fact they are not the same thing. Inversion of Control is a much more general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control.

The application objects must be aware of one another and communicate with one another to get their job done. In an online shopping application, for instance, an order manager component may need to work with a product manager component and a credit card authorization component. All of these will likely need to work with a data access component to read from and write to a database.

The act of creating such associations between application objects is commonly referred to as wiring which is the essence of dependency injection (DI).

The container will create the objects, wire them together, configure them, and manage their complete lifecycle from cradle to grave (or new to finalize ()).

Spring supports two types of dependency injection

1. Setter Injection(Through setter methods of spring bean class)

2. Constructor Injection (Through parameterized constructor of spring bean class)

We will learn about these in coming chapters.

 

 


All Chapters
Author