Spring – Dependency Injection using Inversion of Control

What is Dependency Injection ?

“Dependency Injection”, the word itself clarifies that we are trying to Inject the dependency between the Parent Classes and the calling Class.  But how spring provides it as a Feature and how it is different from previous implementation, is what we need to understand.

Java Programming Concept is all about the object oriented programming, class instantiation, encapsulation and polymorphism. Spring also executes on the same implementation but it provides a simple approach where it allows to make a class independent from its dependencies. To achieve this and make classes loosely decoupled, Spring separates the class creation and class usage (invoked by another dependent class).

Dependency Injection is implemented by using the technique termed as ‘Inversion of Control’. First, we need to understand how IoC Container uses the Spring Framework.

How IoC Container uses the Spring Framework ?

Core Packages: The org.springframework.beans and org.springframework.context packages are the Core Component for Spring Framework IoC Container execution.

Bean Factory: The advanced configuration capability comes from the usage of the BeanFactory. It acts as a Factory class and provides Bean Definition for the multiple application beans and create instances of the bean whenever is requested by the client call.   

Application Context: The ApplicationContext provides access to the bean methods, loading file resources, publishing events, message resourcing supporting internationalization, parent context inheritance for easy integration.

Application Context implementatio n

The ApplicationContext provides the below given commonly used implementation:

  1. ClassPathXmlApplicationContext:  loads the context definition for the application by retrieving it from the XML File.
<strong>ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");</strong>
  • FileSystemXmlApplicationContext: loads the context definition for the application by retrieving it from the XML File placed in the File System.
<strong>ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");</strong>
  • XmlWebApplicationContext: loads the context definition for the application by retrieving it from the XML File within the web application.
<strong>&nbsp;ApplicationContext context = new XmlWebApplicationContext ("bean.xml");</strong>

Below given are the possible ways for implementing the Inversion of Control (Spring IoC Container):

  1. With the usage of Factory Pattern
  2. With the usage of Service Locator Pattern
  3. With the Inclusion of Dependency Injection through
  • The Constructor Injection
  • The Setter Injection
  • The Interface Injection

Dependency Injection – using Constructor Injection