Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC)

The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done simply by an argument-constructor, argument to a factory method, or by setting properties of the objects when they are being constructed. The dependencies are injected by the container when the bean is created. The Inversion of Control (IoC) can be achieved through various techniques, such as Dependency Injection (DI), Service Locator Pattern (SLP), and Strategy Design Pattern (SDP).

The Inversion of Control (IoC) can also be defined as the design process of externalizing the construction and management of the objects. It is an approach to outsourcing the creation and management of the objects. The object factory handles outsourcing.

We can also define the Inversion as a reversal of the legacy. The legacy is to declare and initialize the variables through the instances of the objects we create.

There are two types of IoC containers:

  • BeanFactory - The BeanFactory interface is available in the org.springframework.beans package. It is the root interface for accessing the Spring bean container. It also provides basic configuration techniques to manage the bean objects of any type. We can say that BeanFactory is a legacy method to use.
  • ApplicationContext –The ApplicationContext interface is available in the org.springframework.context package. It is a complete superset of a BeanFactory interface. It is also known as a central interface that provides the configuration to an application.

The following code shows the instantiation of the BeanFactory interface:

The XmlBeanFactory is the implementation class used to initialize the BeanFactory interface.

Resource resource = new FileSystemResource("beanfactory.xml");
XmlBeanFactory fact = new XmlBeanFactory(resource); 

OR

ClassPathResource resource = new ClassPathResource("beanfactory.xml");
XmlBeanFactory fact = new XmlBeanFactory(resource); 

The following code shows the instantiation of the ApplicationContext interface:

The ClassPathXmlApplicationContext is the implementation class used to initialize the ApplicationContext interface.

ClassPathXmlApplicationContext  applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

OR

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

Difference between ApplicationContext and BeanFactory

As we have discussed above that both the ApplicationContext and BeanFactory are the Java interfaces and, both are the types of IoC container. But the main difference between both the interfaces is, the BeanFactory provides the basic IoC and DI features whereas, the ApplicationContext delivers the advanced features.

Some of Other differences are given below:

  • BeanFactory interface does not support internationalization (i18n), whereas ApplicationContext provides support for it. Internationalization is the process of constructing an application in such a way that any languages can adapt it without any modifications.
  • BeanFactory interface uses lazy initialization technique, whereas ApplicationContext uses eager initialization, i.e., BeanFactory creates only a singleton bean when requested, but ApplicationContext produces all singleton beans at the time of initialization.
  • BeanFactory does not support annotation-based configuration, whereas ApplicationContext supports annotations such as @Autowired, @ComponentScan, etc.

Example of IoC (Inversion of Control)

Now, we are going to create an example of Inversion of Control (IoC). In this example, we are going to create the following Classes and Interfaces:

  1. Sim Interface
  2. Jio Class
  3. Airtel Class
  4. applicationContext XML File
  5. AppTest Class

The first step is to add Spring Framework dependencies in pom.xml. To develop any Spring application, we need to add the spring-web MVC dependency.

Following is the dependency required by the application :


 
 org.springframework
 spring-webmvc
 5.1.6.RELEASE
  

The Sim Interface contains three unimplemented methods call(), message(), and dataUsage().

Sim.java

public interface Sim {
             public void call();
             public void message();
             public void dataUsage();  
  } 

The Jio.java is a POJO/ Bean class which implements the Sim interface and overrides its unimplemented methods.

Jio.java

public class Jio implements Sim {
             public void call() {
                         System.out.println("calling through jio");
             }
             public void message() {
                         System.out.println("messaging through jio");
             }
             public void dataUsage() {
                         System.out.println("dataUsage through Jio"); 
             }
   } 

The Airtel.java is a POJO/ Bean class which implements the Sim interface and overrides its unimplemented methods. It is similar to the Jio class.

Airtel.java

public class Airtel implements Sim {
             public void call() {
                         System.out.println("calling through airtel");
             }
             public void message() {
                         System.out.println("messaging through airtel");
             }
             public void dataUsage() { 
                         System.out.println("dataUsage through airtel");
             }
  } 

The applicationContext.xml is a Spring IoC Container which contains the bean objects. In this file, we have added the entry of the Jio class as a bean. All the beans are defined inside the <bean>…</bean> tag.

applicationContext.xml


 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
 
  

The AppTest.java is the main class which contains the main() method. In this class, we have instantiated the ApplicationContextContainer through its implementation class ClassPathXmlApplicationContext.

AppTest.java

import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;
 public class AppTest 
 {
             public static void main(String[] args) {
           //create a Spring container 
                     ClassPathXmlApplicationContext applicationContext = new    ClassPathXmlApplicationContext("applicationContext.xml"); 
             System.out.println("config is loaded");
            //retrieving bean from the Spring container
              Sim sim = applicationContext.getBean("simID", Sim.class);
             sim.call();
             sim.message();
             sim.dataUsage();
             }
 } 

The following code shows that the application is configurable. We can easily change the Sim from Airtel to Jio.

ApplicationContext applicationContext = new    ClassPathXmlApplicationContext("applicationContext.xml");

To change the Sim, we only need to change the bean in the applicationContext file.

OUTPUT

applicationContext

Related Topics

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring Autowiring

Spring Autowiring Autowiring is an essential feature of the Spring framework. The autowiring function is used for wiring beans automatically, without injecting the beans using <constructor-arg> and <property> elements in the bean-config file. It can...

3 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring - Inversion of Control (IoC)

Spring - Inversion of Control (IoC) The Inversion of Control (IoC) is a process where the objects define their dependencies, that is, the dependencies of other objects with they are working. It is done...

4 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring Autowiring – Constructor Injection

Spring Autowiring – Constructor Injection We have previously discussed an example of Constructor Dependency Injection (CDI) using an XML-based configuration. In the previous case, we have defined the reference of the constructor in...

2 minutes read.

Spring AOP – @Around Advice

Spring AOP – @Around Advice We have discussed in our previous tutorial, the concepts, and terminology of the Spring AOP. Around advice is one of the types of advices. It can be applied to...

4 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring – Dependency Injection

Spring – Dependency Injection One of the main features of Inversion of Control (IoC) is Dependency Injection (DI). It is a process of supplying the dependencies from one object to others. The Spring-Core container...

8 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring MVC Form – Drop-Down List

We have already discussed the Spring MVC form tags available in the form tag library. Form tags are used to develop web applications easily. In this tutorial, we are going to discuss the...

13 minutes read.

Spring MVC Example

Spring MVC Example We have previously discussed the Spring Web MVC framework. In this tutorial, we are going to create a simple example of Spring Web MVC. Following are the steps used to create an example...

2 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring MVC Form Validation

Spring Validation is used to validate the @Controller inputs. It is used to check and accept the user input in any web application. Using Spring validation, we can validate the user input on...

12 minutes read.

Spring MVC Example – Reading HTML Form Data

We have discussed earlier a simple example of Spring MVC in which we have created multiple view pages. Here, we are going to create another Spring MVC example in which we are...

7 minutes read.